带工厂的烧瓶应用程序-单独的路由文件

时间:2020-08-31 22:43:35

标签: python flask routes factory

我正在尝试找出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的过程中,我将提供一些帮助。

预先感谢

1 个答案:

答案 0 :(得分:1)

您可以使用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

这部分是关于如何更好地组织应用程序结构的。

相关问题