| 1 |
import peewee |
| 2 |
from peewee import * |
| 3 |
|
| 4 |
from flask_peewee.exceptions import ImproperlyConfigured |
| 5 |
from flask_peewee.utils import load_class |
| 6 |
|
| 7 |
|
| 8 |
class Database(object): |
| 9 |
def __init__(self, app=None, database=None): |
| 10 |
self.database = None |
| 11 |
self.init_app(app, database) |
| 12 |
|
| 13 |
def init_app(self, app, database=None): |
| 14 |
if app is None: |
| 15 |
self.database = database or Proxy() |
| 16 |
self.Model = self.get_model_class() |
| 17 |
return |
| 18 |
|
| 19 |
if isinstance(self.database, Proxy): |
| 20 |
# We deferred initialization, now initialize the proxy. |
| 21 |
self.database.initialize(database or self.load_database(app)) |
| 22 |
elif self.database is None: |
| 23 |
self.database = database or self.load_database(app) |
| 24 |
self.Model = self.get_model_class() |
| 25 |
elif database: |
| 26 |
raise ImproperlyConfigured('Database plugin has already been initialized.') |
| 27 |
|
| 28 |
self.register_handlers(app) |
| 29 |
|
| 30 |
def load_database(self, app): |
| 31 |
self.database_config = dict(app.config['DATABASE']) |
| 32 |
try: |
| 33 |
self.database_name = self.database_config.pop('name') |
| 34 |
self.database_engine = self.database_config.pop('engine') |
| 35 |
except KeyError: |
| 36 |
raise ImproperlyConfigured('Please specify a "name" and "engine" for your database') |
| 37 |
|
| 38 |
try: |
| 39 |
self.database_class = load_class(self.database_engine) |
| 40 |
assert issubclass(self.database_class, peewee.Database) |
| 41 |
except ImportError: |
| 42 |
raise ImproperlyConfigured('Unable to import: "%s"' % self.database_engine) |
| 43 |
except AttributeError: |
| 44 |
raise ImproperlyConfigured('Database engine not found: "%s"' % self.database_engine) |
| 45 |
except AssertionError: |
| 46 |
raise ImproperlyConfigured('Database engine not a subclass of peewee.Database: "%s"' % self.database_engine) |
| 47 |
|
| 48 |
return self.database_class(self.database_name, **self.database_config) |
| 49 |
|
| 50 |
def get_model_class(self): |
| 51 |
class BaseModel(Model): |
| 52 |
class Meta: |
| 53 |
database = self.database |
| 54 |
|
| 55 |
return BaseModel |
| 56 |
|
| 57 |
def connect_db(self): |
| 58 |
if self.database.is_closed(): |
| 59 |
self.database.connect() |
| 60 |
|
| 61 |
def close_db(self, exc): |
| 62 |
if not self.database.is_closed(): |
| 63 |
self.database.close() |
| 64 |
|
| 65 |
def register_handlers(self, app): |
| 66 |
app.before_request(self.connect_db) |
| 67 |
app.teardown_request(self.close_db) |