Last active
December 10, 2015 10:59
-
-
Save miku/4424587 to your computer and use it in GitHub Desktop.
This file contains 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, g, request | |
from flask.views import MethodView | |
import random | |
app = Flask(__name__) | |
NoSQLStore = {} | |
class NoSQL(object): | |
""" fake """ | |
def query(self, key): | |
return '%s\n' % NoSQLStore.get(key, 'no such key') | |
def put(self, key, value): | |
NoSQLStore[key] = value | |
def with_database(fn): | |
""" Decorator for functions, that need database access. | |
NoSQL object will be stored under ``g.db``. | |
""" | |
def connect_and_close(*args, **kwargs): | |
g.db = NoSQL() | |
__result = fn(*args, **kwargs) | |
# a real database should be ``closed()`` here | |
return __result | |
return connect_and_close | |
class StoreAPI(MethodView): | |
@with_database | |
def get(self): | |
return g.db.query(request.args.get('key')) | |
@with_database | |
def post(self): | |
key, value = str(random.randint(0, 1000)), str(random.randint(0, 1000)) | |
g.db.put(key, value) | |
return 'set %s => %s\n' % (key, value) | |
@app.route('/') | |
@with_database # uncomment this to mak | |
def index(): | |
# this should raise an exception, since db object is not in the | |
# request-bound ``g`` object | |
return g.db.query('xyz') | |
app.add_url_rule('/store', view_func=StoreAPI.as_view('store')) | |
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