我在下面构建了一个GET和PUT请求:
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
userStorage =[
{
"id": "1234",
"currentBot": "BestBot"
}
]
class User(Resource):
def get(self, id):
for user in userStorage:
if(id == user["id"]):
return user, 200
return "User not found", 404
def put(self, id):
parser = reqparse.RequestParser()
parser.add_argument("currentBot")
args = parser.parse_args()
for user in userStorage:
if(id == user["id"]):
user["currentBot"] = args["currentBot"]
return user, 200
user = {
"id": id,
"currentBot": args["currentBot"]
}
userStorage.append(user)
return user, 201
def delete(self, id):
global userStorage
userStorage = [user for user in userStorage if user["id"] != id]
return "{} is deleted.".format(id), 200
api.add_resource(User, "/user/<string:id>")
app.run(debug = True, port = 4000)
当我执行一个简单的get请求时,邮递员可以正确地获得响应200,但是当我尝试通过自己的程序进行请求时,它将返回404
import requests
payload2Storage = {
"currentBot": "BestBot"
}
headers = {"Content-Type": "application/json"}
params = {
"id": "1234"
}
#response = requests.request("PUT", "http://127.0.0.1:4000/user/", data=payload2Storage, params=params, headers=headers)
response2 = requests.request("GET", "http://127.0.0.1:4000/user/", params=params, headers=headers)
我从userStorage获取信息的请求有问题吗?
答案 0 :(得分:1)
在客户端代码中,从127.0.0.1
更改为localhost
对我有用。试试这个:
response2 = requests.request("GET", "http://localhost:4000/user/", params=params, headers=headers)
或在服务器代码中,通过主机参数将服务器明确绑定到127.0.0.1,如下所示:
app.run(debug = True, port = 4000, host='127.0.0.1')
代码中的其他错误是user [“ id”]返回一个str,而id是一个int,请按如下所示更改代码:
def get(self, id):
for user in userStorage:
if(id == int(user["id"])):
return user, 200
return "User not found", 404