如何解决带工厂的烧瓶应用程序-单独的路由文件
我正在尝试找出flask应用程序的文件结构。 我用了flask-dotenv,FLASK_APP是main.py
myapp / .flaskenv-指定FLASK_APP myapp / main.py myapp / app / init .py-具有create_app()函数。这也会从db.py导入数据库 myapp / app / db.py-与数据库相关的功能
我想将所有路由都放在单独的routes.py文件中(而不是在create_app()方法中)。 myapp / app / routes.py
在寻找如何链接此route.py的过程中,我将提供一些帮助。
预先感谢
解决方法
您可以使用blueprint
来组织和注册您的路线。
基本上,您可以具有如下所示的文件夹结构:
app/ <-- your entire application folder
auth/ <-- blueprint package for /auth route
__init__.py <-- blueprint creation
routes.py <-- authentication routes
profile/
__init__.py <-- blueprint package for /profile route
routes.py <-- profile routes
__init__.py <-- ceate_app and blueprint registration
在您的路线套餐下,例如位于auth
文件夹中:
# app/auth/__init__.py
# this is initialize auth blueprint
from flask import Blueprint
bp = Blueprint('auth',__name__,)
from app.auth import routes
然后,您可以将所有authentication
路由放入auth/routes.py
,但是除了使用app.route
之外,还需要像这样使用bp.route
:
# app/auth/routes.py
# this is where you can put all your authentication routes
from app.auth import bp
# notice here the route '/login' is actually prefixed with 'auth'
# because in the following code I added "url_prefix='/auth' " in the create_app() factory.
# the full routes will be 'auth/login' on your website.
@bp.route('/login',methods=['GET','POST'])
def login():
....your login code...
然后在您的__init__.py
中,您可以执行以下操作:
# app/__init__.py
from app.auth import bp as auth_bp
from app.profile import bp as profile_bp
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(auth_bp,url_prefix='/auth')
app.register_blueprint(profile_bp,url_prefix='/profile')
这样,到yourdomain.com/auth/...
的所有路由都将在app/auth/routes.py
中;所有到yourdomain.com/profile/...
的路线都在您的app/profile/routes.py
中。
查看有关Flask的精彩教程,了解更多详细信息:
Flask mega tutorial by Miguel Grinberg
这部分是关于如何更好地组织应用程序结构的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。