I built a simple permissions system for my current Flask project, and I would like to break it out into an extension so that I can share it and use it in other projects. I'm struggling with how I might get the user's SQLAlchemy database connection for use in my extension.
Specifically, I'd like to create some models in the database for anyone using my extension. I'm sure there's a pattern for doing this, but I'm not aware of it.
I included some more info here http://bit.ly/1dqubJQ
A pattern that I like for this kind of problem is to not have the extension define database models but instead provide mixin class(es) from which the developer can inherit the models from. In addition to the mixin(s) you can have callback functions for operations like loading or saving models from the database, also to be provided by the app developer.
This technique is used by Flask-Login, for example. I like it because it makes the extension database agnostic. You said you are interested in doing this for SQLAlchemy, but if you publish your extension someone at some point will want to use it with Mongo, or Peewee or without an ORM layer. All these will be supported if you make no assumptions about database engine in the extension.
You just want the user to be able to use their sqlalchemy connection in your extension right ? Why not put it in the init ?
class FlaskExtension(object): # db below is the user's sqlalchemy connection def __init__(self, app=None, db=None): self.app = app self.db = db if app is not None and db is not None: self.init_app(app,db)