Created
November 28, 2014 07:04
-
-
Save kxxoling/0d0c437e6a1fa667fe70 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify, abort, make_response | |
app = Flask(__name__) | |
tasks = [ | |
{ | |
'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 | |
} | |
] | |
mime_types = dict( | |
json_render=('application/json',), | |
xml_render=('application/xml', 'text/xml', 'application/x-xml'), | |
) | |
render_json = jsonify | |
render_xml = lambda msg: '<message>%s</message>' % msg | |
render_txt = lambda msg: msg | |
render_html = lambda msg: '<html><body>%s</body></html>' % msg | |
mime_renders = dict( | |
json=render_json, | |
xml=render_html, | |
txt=render_txt, | |
) | |
def prep_response(rsp, status=200): | |
mime = 'txt' | |
render = get_best_render(rsp) | |
rsp = make_response(render, status) | |
rsp.mimetype = mime | |
return rsp | |
def get_best_render(mime): | |
return render_txt | |
@app.before_request | |
def before(): | |
print 'The request comes!', request | |
@app.after_request | |
def after(response): | |
print 'The request goes away!', response | |
return response | |
@app.route('/') | |
def index(): | |
return 'hello world' | |
@app.route('/todo/<int:task_id>', methods=['GET']) | |
def get_task(task_id=0): | |
task = filter(lambda t: t['id'] == task_id, tasks) | |
if task: | |
return task and jsonify({'tasks': task[0]}) | |
abort(404) | |
@app.route('/todo', methods=['POST']) | |
def create_task(): | |
if not request.json or 'title' not in request.json: | |
abort(400) | |
task = dict( | |
id=len(tasks)+1, | |
title=request.json.get('title'), | |
) | |
tasks.append(task) | |
return jsonify({'task': tasks}), 201 | |
@app.errorhandler(404) | |
def not_found(error): | |
return make_response(jsonify(dict(error='Not Found')), 404) | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment