Skip to content

Instantly share code, notes, and snippets.

@blurrcat
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blurrcat/1650d8960a2dffe6f3af to your computer and use it in GitHub Desktop.
Save blurrcat/1650d8960a2dffe6f3af to your computer and use it in GitHub Desktop.
Deferred database initialization for flask-peewee.db.Database
from flask import Flask
from db import db
def create_app(config_obj)
app = Flask('tets')
app.config.fromobj(config_obj) # db configured in `config_obj`
db.init_app(app)
from flask_peewee.db import Database
from peewee import Model
class DeferredDatabase(Database):
def __init__(self, app=None):
if app:
super(DeferredDatabase, self).__init__(app)
else:
class BaseModel(Model):
pass
self.Model = BaseModel
def init_app(self, app):
self.app = app
self.load_database()
self.register_handlers()
class Meta:
database = self.database
self.Model.Meta = Meta
db = DeferredDatabase()
# database engine irrelevant model definitions
# i.e., you can define models before connecting to the database
from db import db
class User(db.Model):
class Meta:
db_table = 'test_user'
name = CharField()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment