【问题标题】:Python http post request format form dataPython http post请求格式表单数据
【发布时间】:2017-10-17 09:12:31
【问题描述】:

问题描述
我想向在线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"}

显然,表单数据的错误格式会导致这些问题,但我不知道我应该如何格式化(以及这是否能解决问题)

【问题讨论】:

    标签: python post request http-post


    【解决方案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'
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我已经读过,但答案不起作用,这将产生一个错误:{“error”:{“name”:“JSONRPCError”,“message”:“解析JSON时出错HTTP 请求:格式错误的 JSON 字符串,既不是标记、数组、对象、数字、字符串也不是原子,位于 /disks/patric-common/runtime/lib/perl5 的字符偏移量 0(在 \"method=HomologyServi...\" 之前) /site_perl/5.20.2/x86_64-linux/Moose/Meta/Method/Delegation.pm 第 110 行。\n","code":-32700},"version":"1.1","id":"27057295081137034" }
      • @CodeNoob,检查我的答案,如果它不起作用,那么让我知道我可以发布另一个解决方案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      相关资源
      最近更新 更多