KexAri KexAri - 14 days ago 5
Python Question

Splitting a Flask app into multiple files

I am playing around with flask. My directory structure is like so:

|--------flask-test
|----------------app
|-----------------------static
|-----------------------templates
|-----------------------venv
|-----------------------__init__.py


The
venv
folder holds my virtual flask installation. My
__init__.py
is like so:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()


This works with no issues however now I would like to split this into two files
__init__.py
and
main.py
. The
main.py
would be in the same directory as
__init__.py
. So far I have tried:

__init__.py
:

from flask import Flask

app = Flask(__name__)
import main


main.py
:

from app import app
@app.route("/")
def hello():
return "Hello World!"


However I am getting an error that the module
app
does not exist in
main.py
then I try to run
__init__.py
. What am I doing wrong here? Also where should I put the run method?

Answer

Use Flask blueprints

file1:

from flask import Blueprint, render_template, session,abort

app_file1 = Blueprint('app_file1',__name__)
@app_file1.route("/hello")
def hello():
    return "Hello World from app 1!"

file2:

from flask import Blueprint, render_template, session,abort

app_file2 = Blueprint('app_file2',__name__)
@app_file2.route("/world")
def world():
    return "Hello World from app 2!"

file3

from flask import Flask
from file1 import app_file1
from file2 import app_file2
main_app = Flask(__name__)
main_app.register_blueprint(app_file1)
main_app.register_blueprint(app_file2)
Comments