简体   繁体   English

在Python中使用请求模块时遇到问题

[英]Trouble using Requests module in Python

I am trying to use requests to post JSON data to a HTTP endpoint, but I get this weird errors now( I used it before with no problems). 我正在尝试使用请求将JSON数据发布到HTTP端点,但是现在出现了这个奇怪的错误(我以前使用它时没有问题)。

Any troubleshooting is much appreciated. 非常感谢任何故障排除。

The code: 编码:

req = requests.post(HTTP_ENDPOINT, data=json.dumps(data))

Output: 输出:

AttributeError: module 'requests' has no attribute 'post' AttributeError:模块“ requests”没有属性“ post”

Did you write import requests at the top of the file? 您是否在文件顶部写入了import requests If not, that's your problem. 如果没有,那是你的问题。 If yes, then the next step of debugging for me would be to do print dir(requests) since that will tell you what attributes your requests object actually has. 如果是,那么对我来说,下一步的调试将是执行print dir(requests)因为这将告诉您您的请求对象实际上具有哪些属性。

Sure that HTTP_ENDPOINT and data are valid , should like below: 确保HTTP_ENDPOINT和数据有效,应如下所示:

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically: 除了自己编码dict外,您还可以使用json参数(在2.4.2版中添加)直接传递dict,它将自动进行编码:

>>> r = requests.post(url, json=payload)

source is More complicated POST requests 来源是更复杂的POST请求

If you have a file called requests.py in your folder, then python will import that as a module before the requests package that you've installed with pip. 如果您的文件夹中有一个名为request.py的文件,那么python会将其作为模块导入,并随您使用pip安装的请求包一起导入。

That is why it says requests has no attribute 'post'. 这就是为什么说请求没有属性“ post”的原因。 If you define a variable in your requests.py like this: 如果您在request.py中定义一个变量,如下所示:

# requests.py
post = lambda *arg: print('unitended concequence')

You will likely see it print out that statement instead of complaining that post requests does not contain post. 您可能会看到它打印出该语句,而不是抱怨发布请求中不包含发布。 The solution is to rename your files so they don't shadow the packages you want to import. 解决方案是重命名文件,以使它们不会遮盖要导入的软件包。 For instance change requests.py to my_requests.py. 例如,将requests.py更改为my_requests.py。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM