使用 python 而不是flask run 运行flask 应用程序

gxv*_*xvr 5 python sqlalchemy flask

我正在尝试使用“ python app.py ”而不是“ flask run ”命令运行我的烧瓶应用程序。

我的目标是在 cpanel 服务器上启动应用程序,几乎每个教程都要求使用“python”方法调用应用程序。

这是我的文件夹结构:

  • 项目
    • 网络应用程序
      • 初始化.py
      • 模板
      • 静止的
      • auth.py
      • 主要.py
    • app.py <-------------- 我希望用 python 来调用它,而不是在文件夹外调用 Flask run 命令

这是我的init _.py 文件:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager 

# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()

def create_app():
    
    app = Flask(__name__)
    
    app.config['SECRET_KEY'] = '9OLWxND4o83j4iuopO'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

    # blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
Run Code Online (Sandbox Code Playgroud)

app.py 是:

from webapp import app
Run Code Online (Sandbox Code Playgroud)

我是烧瓶新手,非常感谢任何帮助

Car*_*lio 9

在 init.py 末尾插入对 create_app 的调用:

if __name__ == '__main__':
    create_app().run(host='0.0.0.0', port=5000, debug=True)
Run Code Online (Sandbox Code Playgroud)

if 语句避免多次调用应用程序。只能直接调用。Flask 默认主机是 127.0.0.1 (localhost)。在生产中使用 0.0.0.0 以获得更好的流量监控。默认端口也是 5000,因此由您决定是否包含。为了更好的可读性,您应该明确它。

然后调用它

python webapp/init.py
Run Code Online (Sandbox Code Playgroud)