【问题标题】:Make a post request with File content via Python通过 Python 使用文件内容发出 post 请求
【发布时间】:2015-05-28 16:32:24
【问题描述】:

我有一个带有一个 cookie 的非常大的 POST 数据(超过 100 MB),现在我想通过 Python 将它发送到服务器,POST 请求在这样的文件中:

 a=true&b=random&c=2222&d=pppp

这是我的以下代码,它只发送 Cookie 而不是 POST 内容。

import requests
import sys
count = len(sys.argv)
if count < 3:
    print 'usage a.py FILE URL LOGFILE'
else:
    url = sys.argv[2]
    data= {'file': open(sys.argv[1], 'rb')}
    cookies = {'session':'testsession'}
    r = requests.get(url, data=data, cookies=cookies)
    f = open(sys.argv[3], 'w')
    f.write(r.text)
    f.close()

代码获取包含 POST 数据的 File,然后是发送它的 URL,然后是存储响应的 OUTPUT 文件。

注意:我不是要上传文件,而是要发送文件内的帖子内容。

【问题讨论】:

    标签: python file post cookies http-post


    【解决方案1】:

    首先你应该使用requests.post。其次,如果您只想在文件中发布数据,您需要读取文件的内容并将其解析为dict,因为这是requests.post 期望数据进入的格式。

    示例:(注:仅显示相关部分)

    import urlparse
    import requests
    import sys
    
    with open(sys.argv[1], 'rb') as f:
        data = urlparse.parse_qs('&'.join(f.read().splitlines()))
    
    r = requests.post(url, data=data, cookies=cookies)
    

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 2018-04-20
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多