Run flask app with python instead of flask run

Viewed 5451

I'm trying to run my flask app with "python app.py" instead of "flask run" command.

My goal is to launch the app on cpanel server and just about every tutorial requires the applications to be called using the "python" method.

Here is my folder structure:

  • project
    • webapp
      • init.py
      • templates
      • static
      • auth.py
      • main.py
    • app.py <-------------- I want this to be called with python instead of flask run command outside the folder

Here is my init_.py file:

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

And app.py is:

from webapp import app

I'm a newbie in flask, any help is appreciated

1 Answers

Insert the call to create_app at the end of init.py:

if __name__ == '__main__':
    create_app().run(host='0.0.0.0', port=5000, debug=True)

The if statement avoid calling the app many times. It can only be called directly. Flask default host is 127.0.0.1 (localhost). Use 0.0.0.0 at production for better traffic monitoring. Default port is also 5000, so it's up to you to include. For better readability, you should explicit it.

Then call it

python webapp/init.py
Related