例子1
from flask import Flask, jsonify app = Flask(__name__) tasks = [
{
'id': ,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': ,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
] @app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks}) if __name__ == '__main__':
app.run(debug=True)
运行
python test.py
打开浏览器,访问:http://localhost:5000/todo/api/v1.0/tasks
例子2
from flask import Flask, jsonify
from flask import abort
app = Flask(__name__) tasks = [
{
'id': ,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': ,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
] @app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks}) @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = list(filter(lambda t: t['id'] == task_id, tasks))
if len(task) == :
abort()
return jsonify({'task': task[]})
if __name__ == '__main__':
app.run(debug=True)
例子3
from flask import Flask, jsonify
from flask import abort
from flask import make_response
app = Flask(__name__) tasks = [
{
'id': ,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': ,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
] @app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks}) @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = list(filter(lambda t: t['id'] == task_id, tasks))
if len(task) == :
abort()
return jsonify({'task': task[]}) @app.errorhandler()
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), )
if __name__ == '__main__':
app.run(debug=True)