【发布时间】:2020-04-07 02:02:31
【问题描述】:
我正在尝试在我的代码中使用 POST URI 来访问 NCBO 的注释器工具。我当前的代码是 GET 请求,但我不知道如何将其格式化为 POST 请求。我的数据是文本变量。
我看到的所有示例都使用request.get(url) -> request.post(url, data=data),但我该如何为build_opener() 和json.loads() 执行此操作?
这是我的代码:
def get_json(url):
#get annotations
opener = urllib.request.build_opener()
opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)]
return json.loads(opener.open(url).read())
text = "random text with a lot of words"
annotations = get_json("http://data.bioontology.org/annotator?text=" + urllib.parse.quote(text))
更新代码:
def get_annotations(text, url):
headers = [('Authorization', 'apikey token=' + API_KEY)]
data = text
response = requests.request("POST",url,headers=headers,data=data)
return response.text.encode('utf-8')
annotations = get_annotations(text, "http://data.bioontology.org/annotator?text=" + urllib.parse.quote(text))
错误:
response = requests.request("POST",url,headers=headers,data=data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/sessions.py", line 516, in request
prep = self.prepare_request(req)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/sessions.py", line 449, in prepare_request
p.prepare(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py", line 315, in prepare
self.prepare_headers(headers)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py", line 447, in prepare_headers
for header in headers.items():
AttributeError: 'list' object has no attribute 'items'
【问题讨论】:
标签: python python-3.x post get uri