Open arnuschky opened 11 years ago
To be more specific: the only solution I came up with to date is the following.
In models.py, I have this header doing the app-specific import:
try:
from app1 import db
print "loading db wrapper for app1"
except ImportError:
try:
from app2 import db
print "loading db wrapper for app2"
except ImportError:
print "creating db wrapper for normal scripts"
class Database(object):
def __init__(self):
// init database as you need
self.database = SqliteDatabase(...)
self.Model = self.get_model_class()
def get_model_class(self):
class BaseModel(Model):
class Meta:
database = self.database
return BaseModel
db = Database()
This works fine, but is obviously everything but elegant. Any ideas/hints on this?
Ohhhh... I see your point. I think this has been brought up in connection with flask-sqlalchemy as well. You could always just write your models as regular models -- the only thing the flask-peewee database wrapper really does for you is:
You could even do this:
db = Database(app)
# subclass regular peewee.Model
class BaseModel(Model):
class Meta:
database = db.database
# Now you can subclass BaseModel and use those models anywhere.
Sorry for late reply. Our current project is running fine with the hack I described earlier, so it's not urgent to fix it.
Nevertheless, I spotted the activity on https://github.com/coleifer/flask-peewee/issues/69 and I think that they are related. It would be great if we could find a way to do configuration independent of a given app, and independent of the usage of flask at all (i.e., only use the peewee models in a separate non-web app).
I am not sure if this is the right place to ask as it's more of a "best practice" question. Please point me in the right direction if I should go ask somewhere else.
In a given project, there might be multiple apps that use the same data model. For example, the admin interface, the actual flask application, and some helper scripts. Ideally, they should share the same peewee models. This works fine if the database is configured and set within the models.py.
This clashes though with the flask way of doing things. More specifically, flask-peewee requires me to use the database wrapper, something that can't be used in a non-flask application.
Furthermore, in order to avoid circular inputs, an approach like this is required: http://charlesleifer.com/blog/structuring-flask-apps-a-how-to-for-those-coming-from-django/ , which is again incompatible with shared models.
What is the best practice to share the same peewee models across multiple apps/programs?