如何使用python请求模块将表单数据变量添加到post请求?

时间:2014-06-12 21:17:44

标签: python post file-upload request

我正在尝试创建一个命令行实用程序,使用Python的requests模块将文件上传到tempsend.com。

我已经阅读了文档,看起来我想要完成的工作应该很简单,但我无法成功发布该文件。

以下是我尝试过的一些格式:

>>> import requests
>>> url = "http://tempsend.com/send"
>>> payload = {'file': open('happy.txt', 'rb'), 'expire': '2678400'}
>>> r = requests.post(url, data=payload)
>>> r.url
u'http://tempsend.com/error-nopostdata'

>>> files = {'file': open('happy.txt', 'rb'), 'expire' : '2678400'}
>>> r = requests.post(url, files=files)
>>> r.url
u'http://tempsend.com/error-badsecondsvalue'

看起来'expire'字段无法识别。

我认为这是一个有效的原始请求应该是这样的:

POST /send HTTP/1.1
Host: tempsend.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://tempsend.com/
Cookie: __utma=151760572.1993029721.1402528667.1402603529.1402606574.3;         __utmz=151760572.1402528667.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);     __utmb=151760572.2.10.1402606574; __utmc=151760572
Connection: keep-alive
Content-Type: multipart/form-data;     boundary=---------------------------18953598303296896262036228879
Content-Length: 835112

-----------------------------18953598303296896262036228879
Content-Disposition: form-data; name="file"; filename="modules.alias"
Content-Type: application/octet-stream

# Aliases extracted from modules themselves.
alias aes-asm aes_x86_64
alias aes aes_x86_64
alias camellia-asm camellia_x86_64
<blablablablablablablabla>


-----------------------------18953598303296896262036228879
Content-Disposition: form-data; name="expire"

2678400
-----------------------------18953598303296896262036228879--

1 个答案:

答案 0 :(得分:1)

>>> import requests
>>> files = {'file': open('happy.txt', 'rb')}
>>> url = "http://tempsend.com/send"
>>> r = requests.post(url, data={'expire':'2678400'}, files=files)
>>> r.url
u'http://tempsend.com/36DCF220A3'
>>> 

我在问这个问题后5分钟找到了答案..典型!