我正试着在API开发方面有所进展。我大部分的笔记都是从This article开始记的。在
到目前为止,我对GET、POST或{}执行curl requests没有问题。PUT请求返回404错误。在
以下是我正在练习的API代码:class UserAPI(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type = str, required = True, help = "No name provided", location = 'json')
self.reqparse.add_argument('email', type = str, required = True, help = "No email provided", location = 'json')
self.reqparse.add_argument('password', type = str, required = True, help = "No password provided", location = 'json')
super(UserAPI, self).__init__()
def get(self, id):
if checkUser(id): #Just checks to see if user with that id exists
info = getUserInfo(id) #Gets Users info based on id
return {'id': id, 'name': info[0], 'email':info[1], 'password': info[2], 'role': info[3]}
abort(404)
def put(self, id):
if checkUser(id):
args = self.reqparse.parse_args()
deleteUser(id) #Deletes user with this id
addUser(User(args['name'], args['email'], args['password'], args['role'])) #Adds user to database
abort(404)
def delete(self, id):
deleteUser(id)
return { 'result': True}
class UserListAPI(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type = str, required = True, help = "No name provided", location = 'json')
self.reqparse.add_argument('email', type = str, required = True, help = "No email provided", location = 'json')
self.reqparse.add_argument('password', type = str, required = True, help = "No password provided", location = 'json')
self.reqparse.add_argument('role', type = bool, default = 0, location = 'json')
super(UserListAPI, self).__init__()
def get(self):
return { 'users': map(lambda u: marshal(u, user_fields), getAllUsers()) }
def post(self):
print self.reqparse.parse_args()
args = self.reqparse.parse_args()
new_user = User(args['name'], args['email'], args['password'], args['role'])
addUser(new_user)
return {'user' : marshal(new_user, user_fields)}, 201
api.add_resource(UserAPI, '/api/user/', endpoint = 'user')
api.add_resource(UserListAPI, '/api/users/', endpoint = 'users')
基本上,一个类处理查看所有用户或将用户添加到数据库(UserListAPI),另一个类处理获取单个用户、更新用户或删除用户(UserAPI)。在
就像我说的,一切都是有效的。在
当我键入curl -H 'Content-Type: application/json' -X PUT -d '{"name": "test2", "email":"test@test.com", "password":"testpass", "role": 0}' http://127.0.0.1:5000/api/user/2时
我得到以下错误:
^{pr2}$
这对我来说没有意义。不应该接受我放在URL末尾的整数吗?在
谢谢你的任何想法
编辑
在我的一个愚蠢的错误被指出后更新我的答案。现在,put方法如下所示:def put(self, id):
if checkUser(id):
args = self.reqparse.parse_args()
deleteUser(id)
user = User(args['name'], args['email'], args['password'], args['role'])
addUser(user)
return {'user' : marshal(user, user_fields)}, 201
else:
abort(404)