[PYTHON] Tips for building large applications in Flask

Usually in Flask

flask.py


from flask import Flask

app = Flask(__file__)

If you define your application this way, but want to make it with ** MVT **,

blueprint.py


from flask import Blueprint

app = Blueprint("app", __name__, url_prefix="/path")

Define the application in this way.

For example

.
├── app.py
├── model.py
├── static
│   ├── interface.js
│   └── layout.css
├── template
│   ├── design.html
│   └── main.html
└── view
    ├── __init__.py
    ├── api.py
    ├── auth.py
    ├── main.py
    └── setting.py

For such a file structure.

** Define the application with Blueprint for each Python script under view /. ** **

api.py


from flask import Blueprint

app = Blueprint("api", __name__, url_prefix="/api")

You need to register the Blueprint of each Python script under ** view / in ʻapp.py`. ** **

app.py


from flask import Flask
from view import api, auth, main, setting

application = Flask(__name__)

modules_define = [api.app, auth.app, main.app, setting.app]
for app in modules_define:
        application.register_blueprint(app)

First, import each Python script under the view / directory.

from view import api, auth, main, setting

Then ** register the Blueprint application **

application.register_blueprint(app)

Now you can do MVT.

By the way

By the way, instead of registering the Blueprint application under view / directly in ʻapp.py, register the Blueprint application in init.pyunderview / and register it in ʻapp.py. There is also a method of importing with.

__init__.py


from flask import Flask
import api, auth, main, setting

application = Flask(__name__)

modules_define = [api.app, auth.app, main.app, setting.app]
for app in modules_define:
        application.register_blueprint(app)

app.py



from view import application

This may be easier.

Recommended Posts

Tips for building large applications in Flask
Windows → linux Tips for bringing in data
Tips for dealing with binaries in Python
(For myself) Put Flask in VS Code
Tips for making small tools in python
Tips when amateurs use Flask in Visual Studio
Template for creating command line applications in Python
Tips for using Realsense SR300 on MacBook in 2020
Tips for using ElasticSearch in a good way
Library for measuring execution time in Linux C applications
Image uploader in Flask
Tips for handling variable length inputs in deep learning frameworks
Tutorial for doing Test Driven Development (TDD) in Flask-2 Decorators
Building a development environment for Android apps-creating Android apps in Python
(For myself) Flask_8 (Add / Edit / Delete in database with python)
Tips for coding short and easy to read in Python
Tutorial for doing Test Driven Development (TDD) in Flask ―― 1 Test Client