Python http post请求格式表单数据

Python http post请求格式表单数据,python,post,request,http-post,Python,Post,Request,Http Post,问题描述 我想向联机服务器发送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-ww

问题描述
我想向联机服务器发送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"}:
现在我想对几个序列执行此操作(因此替换
atagctaacagccat
)。我熟悉发送此类请求,但现在不知道如何:

  • 格式化
    表单数据
    ,以便使用
  • 我应该如何处理帖子中的
    id
    ,因为我不知道这一点,因为它对于每个爆炸作业都是独一无二的
代码

 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"}

很明显,表单数据的错误格式导致了这些问题,但我不知道应该如何设置格式(如果这样可以解决问题)

您应该更改这一行
res=r.post(blast\u url,headers=headers,params=data)。text
res=r.post(blast\u url,headers=headers,data=data)。text


另外,在使用某些工具之前,请阅读此工具的文档,例如,dosc for requests for requests you can find

您收到格式错误的json字符串,因此远程api希望数据为json格式。你需要做什么

import json
data = json.dumps(data)
res = r.post(blast_url, headers = headers, data = data).text
并将标题的内容类型设置为:

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

我已经读过了,但是答案不起作用,这将产生一个错误:{“error”:{“name”:“JSONRPCError”,“message”:“解析JSON HTTP请求时出错:格式错误的JSON字符串,在字符偏移量0处(在\“method=HomologyServi…\”之前),既不是标记、数组、对象、数字、字符串也不是原子)在/disks/patric common/runtime/lib/perl5/site_perl/5.20.2/x86_64-linux/Moose/Meta/Method/Delegation.pm第110行。\n,“代码”:-32700},“版本”:“1.1”,“id”:“27057295081137034”}@CodeNoob,请检查我的答案,如果它不起作用,请告诉我可以发布另一个解决方案