在进行RESTful Eve项目时,我遇到了一些奇怪的行为
对于这一步,我必须向eve的数据库中添加一些数据。
我想使用python的请求模块对必须保存的数据进行POST
这是我要发送的内容(author
是一个包含一些数据的变量):
data = {"author_id": author.author_id,
"orcid": author.orcid,
"hindex": author.hindex,
"ndocuments": author.hindex,
"ncited_by": author.ncited_by,
"citation_count": author.citation_count,
"current_affiliation": author.affiliation_history[0].affiliation_id,
"affiliation_history": [x.affiliation_id for x in author.affiliation_history],
"subject_areas": [{"name": x[0], "frequency": x[1]} for x in author.subject_areas],
"publication_history": [{"title": x[0], "issn": x[3]} for x in author.publication_history],
"firstname": author.firstname,
"lastname": author.lastname}
r = requests.post('http://localhost:5000/professors', data=data)
return r.status_code
哪个返回422。
发送前,我已经打印了data
包含的内容,看起来像这样
{
"author_id":"57190708172",
"orcid":"",
"hindex":"1",
"ndocuments":"1",
"ncited_by":"18",
"citation_count":"18",
"current_affiliation":"104571568",
"affiliation_history":[
"104571568",
"60022084",
"116039394",
"100252088"
],
"subject_areas":[
{
"name":"Biomaterials",
"frequency":"4"
},
{
"name":"Biomedical Engineering",
"frequency":"4"
}
],
"publication_history":[
{
"title":"Czechoslovak Medicine",
"issn":"01399179"
},
{
"title":"Ceskoslovenska Patologie",
"issn":"00090611"
}
],
"firstname":"Albert Vlastimil",
"lastname":"V\u00e1lek"
}
看起来不错,并包含来自author
的所有数据。现在是我无法理解的问题。
使用requests.post(...)
发送请求始终失败,代码为422 - Unprocessable Entity
,但是从上面限制输出,并使用REST客户端发送请求则效果很好(code 201 - Created
)
这里也是视频https://drive.google.com/open?id=1SwslPKMv0hn1CN8rDnOk7YrTjpr-4OZO
答案 0 :(得分:0)
我认为您需要拨打电话,将正文设置为json
,如下所示:
requests.post('http://localhost:5000/professors', json=data)
答案 1 :(得分:0)
解决了该问题,解决方案是设置标题的内容类型,将数据作为json发送
r = requests.post('http://localhost:5000/affiliation', data=j, headers={'Content-type': 'application/json'})
哪里
j = json.dumps(data)