fromflaskimportFlask,jsonify,abort,request,url_forfromflask.ext.httpauthimportHTTPBasicAuthfromflask.ext.restfulimportApi,Resourceapp=Flask(__name__)api=Api(app)auth=HTTPBasicAuth()@auth.get_passworddefget_password(username):ifusername=='linkoubian':return'7c4a8d09ca3762af61e59520943dc26494f8941b'returnNone@auth.error_handlerdefunauthorized():returnmake_response(jsonify({'error':'Unauthorized access'}),403)# return 403 instead of 401 to prevent browsers from displaying the default auth dialogtasks=[{'id':1,'title':u'Buy groceries','description':u'Milk, Cheese, Pizza, Fruit, Tylenol','done':False},{'id':2,'title':u'Learn Python','description':u'Need to find a good Python tutorial on the web','done':False}]classTaskListAPI(Resource):defget(self):passdefpost(self):passclassTaskAPI(Resource):defget(self,id):passdefput(self,id):passdefdelete(self,id):passapi.add_resource(TaskListAPI,'/todo/tasks',endpoint='tasks')api.add_resource(TaskAPI,'/todo/tasks/<int:id>',endpoint='task')if__name__=='__main__':app.run(debug=True)
提取验证逻辑
然后为TaskListAPI及TaskAPI这两个资源分别添加初始化方法,以处理数据验证等。
TaskListAPI的初始化方法
12345
def__init__(self):self.reqparse=reqparse.RequestParser()self.reqparse.add_argument('title',type=str,required=True,help='No task title provided',location='json')self.reqparse.add_argument('description',type=str,default="",location='json')super(TaskListAPI,self).__init__()