donglu3087 2018-08-03 05:43
浏览 74

无法使用文件向另一个php网站发出POST请求

Recently I have migrate my application from python2/pylons to python3/pyramid.

In my plyons app, I was using below code to make POST request to third party php website (also maintained by me).

     register_openers()

     datagen, headers = multipart_encode({
        "biosamples_metadata": open(file_bs_md, "rb"),
        "metastore": open(file_ds_md, "rb"),
        "annotation-submit": "Validate Annotation Files"
    })

    # Create the Request object
    url = config['php_website_url']
    request = urllib.request.Request(url, datagen, headers)
    # Actually do the request, and get the response
    return_text = urllib.request.urlopen(request).read()
    return return_text

This above code worked perfectly fine. However on python3, poster is not supported and I cannot use register_openers() which I don't even know do what.

In python3, I am using requests module.

import requests
        from requests_toolbelt import MultipartEncoder
        url = config['php_website_url']
        m = MultipartEncoder(
                fields={'biosamples_metadata': open(file_bs_md, 'rb'),
                        "metastore":open(file_ds_md, "rb"),
                        "annotation-submit":  "Validate Annotation Files"
                        }
                )
        request = requests.post(url, data=m)
        return_text = request.text

However, this code does not work properly. It goes to php app and executes the part of the code that is supposed to be executed when you do get request.

Here is what php code look like

      public function handle_request () {

            $TEMPLATE = 'content_main';

            // Process POST
            if ($this->isPOST()) {
                  $this->_annotationFiles = array();
                   return $this->error_span('This is Get');
                 } 
            else ($this->isGET()) {
                  $this->_annotationFiles = array();
                  return $this->error_span('This is Post')
                 } 

Any help appreciated

  • 写回答

1条回答 默认 最新

  • dongxiequ3724 2018-08-10 14:46
    关注

    I am not sure about your PHP code, but the below is the correct way to post files & data to a remote url with Python 3 and requests:

    import requests
    post_addr = "https://example.com/post_url"
    data = {
        'foo': 'bar',
        'foo_a': 'bar_a':
        }
    files = {'file': open('report.xls', 'rb')}
    r = requests.post(post_addr, data=data, files=files)
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)