如何從Flask擴展中訪問SQLAlchemy數據庫?

[英]How do I access the SQLAlchemy database from my Flask extension?


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.

我為我當前的Flask項目構建了一個簡單的權限系統,我想將其分解為一個擴展,以便我可以共享它並在其他項目中使用它。我正在努力獲取用戶的SQLAlchemy數據庫連接以便在我的擴展中使用。

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

我在http://bit.ly/1dqubJQ中添加了一些更多信息

2 个解决方案

#1


3  

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.

我喜歡這種問題的模式是沒有擴展定義數據庫模型,而是提供mixin類,開發人員可以從中繼承模型。除了mixin之外,您還可以為數據庫中的加載或保存模型等操作提供回調函數,也可由應用程序開發人員提供。

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.

例如,Flask-Login使用此技術。我喜歡它,因為它使擴展數據庫不可知。您說您有興趣為SQLAlchemy執行此操作,但如果您發布擴展名,則某人會在某些時候將其用於Mongo或Peewee或沒有ORM層。如果您不對擴展中的數據庫引擎做任何假設,那么所有這些都將得到支持。

#2


2  

You just want the user to be able to use their sqlalchemy connection in your extension right ? Why not put it in the init ?

您只是希望用戶能夠在您的擴展中使用他們的sqlalchemy連接嗎?為什么不把它放在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)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/08/28/72f5a15b2de94c3336cb7293735d392d.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com