gpt4 book ai didi

python - 我如何将 Flask-Admin BaseView 注册为模块

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:52 25 4
gpt4 key购买 nike

如何将 Flask-Admin BaseView 注册为我的应用程序中的模块?每次运行我的应用程序时,我都会收到蓝图碰撞错误!

我也了解 Flask-Admin 中的 ModelView,但我想将模型和 View 彼此分开。

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

├── __init__.py
├── models.py
├── static
├── templates
│ └── user
│ └── index.html
└── views
├── __init__.py
└── user.py

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')

最佳答案

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

我只需要按照描述导入UserView here 。并且还需要在 View 中导入package app。

这是__init__.pyviews/user.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

from Backend import app
from flask_admin import BaseView, expose


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

这部分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.

关于python - 我如何将 Flask-Admin BaseView 注册为模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30110128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com