Issue
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?
Solution
Using Flask blueprints, you can break up your application in multiple files which can be put back together into a larger application.
Below is a sample application broken into 3 files that demonstrates just that:
- file1 : define a /hello route
- file2 : define a /world route
- file3 : main app, acts as a glue by using register_blueprint function to integrate the apps in file1 and file2
file1: defines app_file1 with route /hello
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: defines app_file2 with route /world
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: main app
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)
Note: To simplify things, for this example are kept in a single directory. In a larger application, you would want to further break things into directories/modules. Using modules is extra step allows to only expose the functionality you want public, do extra initialization and avoid circular dependencies.
It is also good practice to have additional folders for things like data access like sqlalchemy models. It's always good to encapsulate files that have common functionality like a payment processing into a module for potential reuse, code clarity and maintenance
If your application has a large amount of views, you may want to have additional subfolders as well
Answered By - Youn Elan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.