简体   繁体   中英

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).

Any troubleshooting is much appreciated.

The code:

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

Output:

AttributeError: module 'requests' has no attribute 'post'

Did you write import requests at the top of the file? 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.

Sure that HTTP_ENDPOINT and data are valid , should like below:

>>> 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:

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

source is More complicated POST requests

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.

That is why it says requests has no attribute 'post'. If you define a variable in your requests.py like this:

# 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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