Python+Requests+Eve:向post发送数据失败,错误代码422

2024-05-16 02:54:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在做我的平安夜计划时遇到了一些奇怪的行为

在这个步骤中,我必须向eve的数据库添加一些数据。在

我想用python的requests模块用我必须保存的数据发布一个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包含的内容打印到控制台,如下所示

^{pr2}$

它看起来很好,并且包含来自author的所有数据。现在有一个我无法理解的问题。 用requests.post(...)发送请求总是失败的,代码是422 - Unprocessable Entity,但是处理上面的输出并用REST客户机发送它是完美的(code 201 - Created

这里还有一个视频https://drive.google.com/open?id=1SwslPKMv0hn1CN8rDnOk7YrTjpr-4OZO


Tags: 数据inid内容fordatabyrequests
2条回答

修正了这个问题,解决方案是设置header的内容类型,将数据作为json发送

r = requests.post('http://localhost:5000/affiliation', data=j, headers={'Content-type': 'application/json'})

在哪里

^{pr2}$

我认为您需要进行requests调用,将body设置为json,如下所示:

requests.post('http://localhost:5000/professors', json=data)

相关问题 更多 >