Python http post请求格式表单数据

时间:2017-10-17 09:12:31

标签: python post request http-post

问题描述
我想向在线BLAST website发送一个http post请求。我检查了POST请求并看到了这个:

Request URL:https://p3.theseed.org/services/homology_service
Referrer Policy:no-referrer-when-downgrade

Request Headers
Provisional headers are shown
Accept:application/json
Content-Type:application/x-www-form-urlencoded
Origin:https://www.patricbrc.org
Referer:https://www.patricbrc.org/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
X-Requested-With:XMLHttpRequest

Form Data
{"method":"HomologyService.blast_fasta_to_database","params":[">test
ATAGCTAACAGCATC","blastn","ref.fna","10",50,0],"version":"1.1","id":"27057295081137034"}:

现在我想为几个序列执行此操作(因此替换ATAGCTAACAGCATC)。我熟悉发送这些类型的请求,但我现在不知道如何:

  • 格式化form data,以便我可以使用Requests
  • 发送
  • 我应该对帖子中的id做些什么,因为我不知道这一点,因为它对每个BLAST作业都是独一无二的。

代码

 import requests as r

blast_url = 'https://p3.theseed.org/services/homology_service'
data = {"method":"HomologyService.blast_fasta_to_database","params":["%3Etest%0ATAGCTAACAGCATC","blastp","ref.faa","10",'50','0'],"version":"1.1"}
headers = {
            'Host': 'p3.theseed.org',
            'Accept': 'application/json',
            'Accept-Language': 'en-US,en;q=0.5',
            'Referer': 'https://www.patricbrc.org/app/BLAST',
            'Content-Type': 'application/rqlquery+x-www-form-urlencoded',
            'X-Requested-With' : 'XMLHttpRequest'
        }

res = r.post(blast_url, headers = headers, params = data).text
print(res)

我没有填写id,但这似乎不是问题,因为在错误消息中填写了ID(所以它似乎自动生成了?) 这是我得到的错误:

{"id":"15004153692662703","error":{"name":"JSONRPCError","code":-32700,"message":"You did not supply any JSON to parse in the POST body."},"version":"1.1"}

显然,表单数据的格式错误会产生这些问题,但我不知道应该如何格式化(如果这样可以解决问题)

2 个答案:

答案 0 :(得分:1)

您输入的json字符串格式错误,因此远程api期望数据为json格式。你需要做

import json
data = json.dumps(data)
res = r.post(blast_url, headers = headers, data = data).text

并将标题的内容类型设为:

headers['Content-Type'] = 'application/json'

答案 1 :(得分:0)

您应该将此行res = r.post(blast_url, headers = headers, params = data).text更改为res = r.post(blast_url, headers = headers, data = data).text

此外,在使用某些工具之前,请阅读此工具的文档,例如,dosc可查找您可以找到的请求here