How to access SQLAlchemy database from my Flask extension?

I built a simple permission system for my current Flask project, and I would like to break it into an extension so that I can share it and use it in other projects. I am struggling with how I can get a user's SQLAlchemy database connection for use in my extension.

In particular, I would like to create some models in the database for those who use my extension. I am sure there is a sample for this, but I do not know about it.

I have included additional information here http://bit.ly/1dqubJQ

+4
source share
2 answers

The sample I like for this problem is to not have the extension defining the database models, but instead provide the mixin (s) class from which the developer can inherit the models. In addition to mixin (s), you can have callback functions for operations, such as loading or saving models from a database, also provided by the application developer.

This method is used, for example, by Flask-Login . I like it because it does agnostic extension database. You said that you are interested in this for SQLAlchemy, but if you publish your extension, at some point someone will want to use it with Mongo, Peewee or without an ORM layer. All of this will be supported if you make no assumptions about the database mechanism in the extension.

+3
source

Do you just want the user to be able to use their sqlalchemy connection in their extension directly? Why not put it in init?

class FlaskExtension(object): # db below is the user 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) 
+2
source

Source: https://habr.com/ru/post/1499435/


All Articles