如何将Flask管理BaseView注册为modu

2024-04-26 21:38:40 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将Flask Admin BaseView注册为应用程序中的模块?每次我运行我的应用程序都会遇到蓝图冲突错误!在

我也知道Flask Admin中的ModelView,但是我想把模型和视图彼此分开。在

init.py

from flask import Flask
import flask_admin as admin
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)


from views.user import user_view, UserView

admin = admin.Admin(app, name='Backend')
user_view.add_view(UserView)

db.create_all()

Package Folder Backend

^{pr2}$

models.py

from . import db


class UserModel(db.Model):
    '__tablename__' == "User"
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(100))
    last_name = db.Column(db.String(100))
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    # Required for administrative interface. For python 3 please use __str__ instead.
    def __unicode__(self):
        return self.username

user.py

from flask_admin import Admin, BaseView, expose
from Backend import app

user_view = Admin(app, name="User")


class UserView(BaseView):
    @expose('/')
    def index(self):
        return self.render('user/index.html')

Tags: namefromimportselfviewappflaskdb
1条回答
网友
1楼 · 发布于 2024-04-26 21:38:40

所以我回答我自己的问题。这只是个谬论。在

我只需要导入UserView,如here所述。还需要在视图中导入包应用程序。在

这里是__init__.py和{}之间的关系。在

init.py

from flask import Flask
import flask_admin as admin
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)


from views.user import UserView

admin = admin.Admin(app, name='Backend')
admin.add_view(UserView(name="User"))

db.create_all()

views/user.py

^{pr2}$

这部分from Flask Documentaion:很有趣。

Circular Imports:

Every Python programmer hates them, and yet we just added some: circular imports (That’s when two modules depend on each other. In this case views.py depends on init.py). Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in init.py and just ensuring the module is imported and we are doing that at the bottom of the file.

相关问题 更多 >