Re: [flask] Re-Usable Components with Flask-SQLAlchemy
- From:
- dag.odenhall@gmail.com
- Date:
- 2011-04-28 @ 12:18
On 28 April 2011 08:09, Nicholas Retallack <nickretallack@gmail.com> wrote:
> The documentation covers breaking your Flask app up into smaller
> pieces using modules, current_app, etc. But what do I do if I want to
> include sqlalchemy models in my components? Or views that use the db
> object? If you're in an external component, you can't really know the
> name of the parent app you'd want to import that db object from, so
> you'd have to fend for yourself.
>
> Having components with their own models is very common in Django. You
> can't even have a Django component without an empty models.py in it.
> Wouldn't it be nice if there were a way to use the Flask-SQLAlchemy
> object in multiple unconnected apps, like you can with the Flask App
> object? current_db, perhaps?
from werkzeug import LocalProxy
from flask import current_app
current_db = LocalProxy(lambda: current_app.extensions['sqlalchemy'].db)
>
> Also, it'd be nice to be able to make foreign key relationships
> between models in unrelated components. For example, you could have a
> small component that handles login and registration by storing the
> user's password hashes and openids in some credentials tables with
> foreign key relationships to the main app's User model. The login
> component doesn't know what the user table is named, or which class is
> the User model, at first. It'd have to register this in some way, and
> update the foreign keys in its models as well as the db.relationships
> to point to that class.
>