""" db.py database interface ... in this example, just stored in a json file Notes : This is *not* a great approach for several reasons, but it's simple and illustrates several basic notions. "g" (think "globals") is a flask special object/dict that stores request data. g['db'] will store our session and form data as a python dictionary. The database itself is stored in an "instance" directory, which is where anything for one deployed instantiation of this app should be put. """ from flask import current_app, g import simplejson def open_db(): """ modify the global "g" object by adding a 'db' (database) key containing the data found by reading the json database """ if 'db' not in g: try: with open(current_app.config['JSONDATA']) as jsonfile: g.db = simplejson.loads(jsonfile.read()) except: g.db = {} def close_db(e=None): """ write the database to the json file, and remove the 'db' key from the global "g" object. """ # (This is called by the flask framework, # which may passes an exception argument which we'll ignore) if 'db' in g: with open(current_app.config['JSONDATA'], 'w') as jsonfile: jsonfile.write(simplejson.dumps(g.db)) g.pop('db', None) def init_app(app): """ initialize any database aspects of this app """ # add "close_db" to the tasks to be done when a request finishes. app.teardown_appcontext(close_db)