首页 > 解决方案 > AttributeError: module 'requests' has no attribute 'post'. is it deprecated and new function has been introduced?

问题描述

I've been trying to send requests to a local server built using flask. requests are sent using requests module of python.

I don't know if that requests.post function has been deprecated and new one's introduced or is there anything really wrong with my code. I've done everything exactly as said in this article.
Here's my code:

import requests

host_url = "http://127.0.0.1:5000"

# get the data
data_for_prediction = [int(input()) for _ in range(10)]
r = requests.post(url=host_url,json={data_for_prediction})
print(r.json())

The error I'm getting for above code is:

Traceback (most recent call last):
  File "C:/Users/--/requests.py", line 1, in <module>
    import requests
  File "C:\Users\--\requests.py", line 8, in <module>
    r = requests.post(url=host_url,json={data_for_prediction})
AttributeError: module 'requests' has no attribute 'post'

Process finished with exit code 1

my server code is:

flask_server_app = Flask(__name__)

# let's make the server now
@flask_server_app.route("/api/predict", methods=["GET", "POST"])
# my prediction function goes here
def predict():
    # Get the data from the POST request & reads the received json
    json_data = request.get_json(force=True)

    # making prediction
    # Make prediction using model loaded from disk as per the data.
    prediction = ml_model.predict([[json_data]])

    # return json version of the prediction
    return jsonify(prediction[0])

# run the app now
if __name__ == '__main__':
    flask_server_app.run(port=5000, debug=True)

I've tried checking documentation, checked many articles online and also re-wrote the whole code. But, none helped.

So, is that requests.post function deprecated and a new one's been introduced or is there anything wrong with my code.

标签: pythonrestflaskpython-requestslocalhost

解决方案


似乎您正在将代码编写在一个名为的文件中,requests.py因此当您尝试导入 requests 模块时,它确实将您自己的文件作为模块导入。尝试重命名您的文件...


推荐阅读