我正在尝试用Flask-RESTful实现一个REST API。我的API包含4个请求:GET、POST、PUT、DELETE。除了PUT请求之外,其他所有操作都很完美。它不断返回状态代码404,但未找到请求的URL。我正在使用Postman来测试我的API。这是我的密码。有人能告诉我哪里做错了吗?非常感谢。
# Small API project using Flask-RESTful
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
app = Flask(__name__)
# Encrypted key
app.secret_key = "Nam Dao"
api = Api(app)
students = []
class Student(Resource):
parser = reqparse.RequestParser()
parser.add_argument("major", type=str, required=True, help="This field cannot be left blank")
def get(self, name):
# filter function will return a filter object
# next function will get the "next" student in the filter object.
# if the Next function does not return anything => return None.
for student in students:
if student["name"] == name:
return student, 200
return {"message": "student not found"}, 404
def post(self, name):
if next(filter(lambda x: x["name"] == name, students), None) is not None:
return {"message": f"A student with the name {name} already exists"}, 400
request_data = self.parser.parse_args()
print(request_data)
student = {"name": name, "major": request_data["major"]}
students.append(student)
return student, 201
def delete(self, name):
for student in students:
if student["name"] == name:
students.remove(student)
return {"message": "Item deleted"}, 200
return {"message": "No student found"}, 204
def put(self, name):
data = request.get_json()
for student in students:
if student["name"] == name:
student["major"] = data["major"]
return {"message": "Student Major Changed"}, 200
student = {"name": data["name"], "major": data["major"]}
students.append(student)
return {"message": "Student Added"}, 200
api.add_resource(Student, "/student/<string:name>")
class StudentsList(Resource):
def get(self):
return {"students": students}, 200
api.add_resource(StudentsList, "/students")
if __name__ == '__main__':
app.run(debug=True)
我再次检查我的URL,发现我缺少一个字母,这就是它返回404状态代码的原因。这是一个非常愚蠢的错误。一切正常