"""
Simple application with flask-peewee where peewee is a Django-like ORM
<http://peewee.readthedocs.org/en/latest/index.html>
<http://flask-peewee.readthedocs.org/en/latest/index.html>
$ pip install flask-peewee
$ python server.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader
"""
import os
from flask import Flask, request, send_from_directory
from flask_peewee.db import Database
from peewee import TextField
app = Flask(__name__)
root = os.path.dirname(__file__)
DATABASE = {
'name': 'example.db',
'engine': 'peewee.SqliteDatabase',
'check_same_thread': False,
}
DEBUG = True
SECRET_KEY = 'shhhh'
app.config.from_object(__name__)
database = Database(app)
class Note(database.Model):
key = TextField(unique=True)
json = TextField()
@app.route('/', methods=["GET", "POST",])
def hello_world():
print "request: ", request.content_type, request.content_length, request.data, ":", request.stream.read()
return request.data
@app.route('/note/<key>/', methods=['GET', 'POST',])
def note(key):
"""
$ curl -i http://localhost:5000/note/miao/ -X POST -d'{"miao": "bau"}' -H "Content-type: raw"
"""
try:
note = Note.get(key=key)
except Note.DoesNotExist:
note = Note.create(key=key, json="{}")
note.save()
if request.method == 'GET':
return note.json
else:
note.json = request.stream.read()
note.save()
return '{}'
@app.route('/librarian/<filename>/', methods=["GET", "POST",])
def librarian(filename):
return send_from_directory(root, filename, as_attachment=True, attachment_filename=filename)
@app.errorhandler(404)
def four_o_four(error):
return '<html><body>you are fucked:' + error.message + '</body></html>', 404
if __name__ == '__main__':
Note.create_table(fail_silently=True)
app.run(debug=T