No Description

db.py 845B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import sqlite3
  2. import click
  3. from flask import current_app, g
  4. from flask.cli import with_appcontext
  5. def get_db():
  6. if 'db' not in g:
  7. g.db = sqlite3.connect(
  8. current_app.config['DATABASE'],
  9. detect_types=sqlite3.PARSE_DECLTYPES
  10. )
  11. g.db.row_factory = sqlite3.Row
  12. return g.db
  13. def close_db(e=None):
  14. db = g.pop('db', None)
  15. if db is not None:
  16. db.close()
  17. def init_db():
  18. db = get_db()
  19. with current_app.open_resource('schema.sql') as f:
  20. db.executescript(f.read().decode('utf8'))
  21. @click.command('init-db')
  22. @with_appcontext
  23. def init_db_command():
  24. """Clear the existing data and create new tables."""
  25. init_db()
  26. click.echo('Initialized the database.')
  27. def init_app(app):
  28. app.teardown_appcontext(close_db)
  29. app.cli.add_command(init_db_command)