为什么我的POST请求似乎不起作用? (Python请求模块)

时间:2015-03-09 14:24:24

标签: python html post python-requests

我现在正尝试使用库请求将多个作业提交到Web服务器http://helios.princeton.edu/CONCORD/

我的代码目前看起来像这样:

import requests

post_url = "http://helios.princeton.edu/CONCORD"
response_email = "email_example@gmail.com"
sequence_example = "MLGDTMSGGIRGHTHLAIMAVFKMSPGYVLGVFLRKLTSRETALMVIGMAMTTTLSIPHDLMELIDGISLGLILLKIVTQFDNTQVG"
job_description = "example"

info = { "sequence_text": sequence_example, "email_address": response_email, "description": job_description }

r = requests.post(post_url, params=info)
print r.status_code
print r.headers

状态返回200,标题返回如下,但服务器不提交作业,因为我的电子邮件没有得到任何回复。

200
{'content-length': '5637', 'x-powered-by': 'PHP/5.3.2', 'server': 'Apache/2.2.3 (Red Hat)', 'connection': 'close', 'date': 'Mon, 09 Mar 2015 14:14:33 GMT', 'content-type': 'text/html; charset=UTF-8'}

任何人都可以帮我解决这个问题并让它发挥作用吗?

1 个答案:

答案 0 :(得分:1)

您正在尝试发送网址查询参数,同时表单会要求您发送multipart/form个编码数据:

<form id="query_form" action="" method="post" enctype="multipart/form-data">

由于表单配置为使用multipart/form-data,您应该使用datafiles来发布这些参数:

r = requests.post(post_url, files=info)

params用于网址参数,即网址?之后的部分。您也可以在POST请求中使用URL参数,但表单数据通常作为正文的一部分发送。使用files参数,即使没有实际的文件数据,也会在此触发multipart/form-data的编码。

使用http://httpbin.org测试服务器,比较以下响应:

>>> import requests
>>> info = {"sequence_text": 'sequence', "email_address": 'email', "description": 'desc'}
>>> print requests.post('http://httpbin.org/post', params=info).text
{
  "args": {
    "description": "desc", 
    "email_address": "email", 
    "sequence_text": "sequence"
  }, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "0", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.5.1 CPython/2.7.9 Darwin/14.3.0"
  }, 
  "json": null, 
  "origin": "81.134.152.4", 
  "url": "http://httpbin.org/post?description=desc&email_address=email&sequence_text=sequence"
}

>>> print requests.post('http://httpbin.org/post', files=info).text
{
  "args": {}, 
  "data": "", 
  "files": {
    "description": "desc", 
    "email_address": "email", 
    "sequence_text": "sequence"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "411", 
    "Content-Type": "multipart/form-data; boundary=be9a69498ab445b1a79282584877b3bf", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.5.1 CPython/2.7.9 Darwin/14.3.0"
  }, 
  "json": null, 
  "origin": "81.134.152.4", 
  "url": "http://httpbin.org/post"
}

请注意url参数的差异,以及第一个请求显示解析为args(来自URL)的参数以及files参数中的另一个参数的事实(来自POST正文,使用multipart/form-data)。另请注意Content-Type(缺少一个)和Content-Length标头的区别。

相关问题