Reputation: 6366
I've been playing around with Flask for the past week. For fun, I'm trying to implement the following. Yes, I know it's very Django-esque, and perhaps inappropriate for a micro-framework.
Here is a sample of what I'm trying to do:
STATIC_PATH = '/static/'
TEMPLATE_URL = '/template/'
DATABASES = {
'DEBUG': {
'ENGINE': 'bla.sqlite3',
'NAME': 'koopics.db'
},
'DEMO': {
'ENGINE': 'bla.sqlite3',
'NAME': 'somedb'
},
'PRODUCTION': {
'ENGINE': 'bla.psycopg2',
'NAME': 'somedb',
'host': 'host',
'username': 'host',
'password': 'host',
},
}
MODE = 'Demo'
#TODO: put an IF statement here to provide the connection mechanism for the db
# depending on what is required
INSTALLED_APPS = [
'Flask-SQLAlchemy',
'Flask-DebugToolbar',
'Flask-Mail',
'Flask-Cache',
'Flask-Celery',
'my_custom_module',
]
I currently have my custom apps defined in their own folder with __init__.py
.
Question: Is it possible to get the DBs to work and have the "apps" loaded as part of settings and app.py?
Upvotes: 0
Views: 338
Reputation: 20353
Your settings are loaded first, before anything else is processed. If you want to switch DBs depending on a request, then you need to put this if
in the model/view logic.
According to the docs (your settings look much more like django
than regular flask
so I'm not sure that this will even work) you can use __bind_key__
in your models to direct that model to a particular DB
# settings.py
SQLALCHEMY_BINDS = {
'DEBUG': 'sqlite:////path/to/koopics.db',
'DEMO': 'sqlite:////path/to/somedb.db'
}
and in you model
# model
class DebugModel(db.Model):
__bind_key__ = 'DEBUG'
id = db.Column(db.Integer, primary_key=True)
debug_value = db.Column(db.String(80), unique=True)
However, if you mean that you want this to access the DB one way for say production, and another for development, then something like
import os
if os.environ('MACHINE_NAME', '') == 'PRODUCTION':
# set up production db
else:
# set up development db
then an if
in your settings is appropriate.
Upvotes: 1