flask 搭建简单restful接口,moco基础

from flask import Flask, jsonify, abort, make_response


app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False #jsonify输出中文不乱码

@app.route('/')
def hello_world():
return 'Hello World!'


tasks = [
{
'id': 1,
'title': 'Buy groceries',
'description': 'Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': 'Learn Python',
'description': '噢噢!',
'done': False
},
{

}
]
#1.路由 2.<>里面为url传入变量,需强转型,默认str
@app.route('/mocoapi/<int:id>',methods=['GET'])
def mocoapi(id):
# if len(tasks[id])<0:#注意这个条件会不会导致正常应该抛404因为不满足这个条件没抛404
# abort(404) #抛出404
return jsonify({'task':tasks[id]})
#自定义404错误
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error':'Not Found'}),'404')


if __name__ == '__main__':
app.run(debug='Ture')
posted @ 2019-12-20 05:37  llm111222333  阅读(332)  评论(0编辑  收藏  举报