[PYTHON] I summarized the folder structure of Flask

A person who develops web systems using Django all the time. I recently started studying Flask because I wanted to make a simple app in my spare time. It's not good to pack too many settings in one file, so I've put together a directory structure based on MVC.

flask_app
├ common
│ ├ libs
│ └ models  ---model
│   ├ user.py
│ └ ・ ・ ・
├ config ---Settings folder
│ ├ base_setting.py ---Common settings for each environment
│ ├ local_setting.py ---Settings for local development environment
│ └ production_setting.py ---Production environment settings
├ controllers ---controller
│ ├ index.py
│ └ ・ ・ ・
├ interceptors 
│ ├ auth.py ---Authentication system processing
│ └ error_handler.py ---Error handling
├ static ---Static file location
├ templates ---template
│ ├ common
│ │ └ layout.html
│ └ index.html
├ application.py ---Define what is used by multiple files (Flask instance, DB, environment variables, etc.)
├ manager.py ---Application execution script (application entrance)
├ requirements.py ---Library list
└ www.py ---routing

Execution flow

Description of file role

I will explain in order.

app.config.from_pyfile("config/base_setting.py")First read the common settings with. The settings that change depending on the environment (development / production) are the environment variables ops set in advance._Changed to read different config file depending on different value of config.




#### **`flask_app/application.py`**
```flask

from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)

manager = Manager(app)
app.config.from_pyfile("config/base_setting.py")

# linux export ops_config=local|production
# windows set ops_config=local|production
if "ops_config" in os.environ:
    app.config.from_pyfile("config/%s_setting.py" % (os.environ['ops_config']))

db = SQLAlchemy(app)

The contents of controllers are divided by function and integrated using blueprint at www.py.

flask_app/www.py


from interceptors.errorHandler import *
from interceptors.Auth import *
from application import app
from controllers.index import index_page

from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)


app.register_blueprint(index_page, url_prefix="/")

Define the model in models. Here, a test model is defined in user.py.

flask_app/common/models/user.py


from application import db


class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), nullable=False)

Define the actual processing in controllers.

flask_app/controllers/index.py


from flask import Blueprint, render_template
from common.models.user import User

index_page = Blueprint("index_page", __name__)


@index_page.route("/")
def index():
    name = "hello"
    context = {"name": name}
    context["user"] = {"nickname": "xxxx",
                       "id": "xxxxx", "home_page": "http://www.xxx"}
    context["num_list"] = [1, 2, 3, 4, 5]

    result = User.query.all()
    context['result'] = result

    return render_template("index.html", **context)

Register the commands runserver and create_all with the manager's add_commend method.

flask_app/manager.py


 from application import app, db, manager
from flask_script import Server, Command
from www import *

# web server
manager.add_command("runserver", Server(host = "0.0.0.0", use_debugger=True, use_reloader=True))

# create tables
@Command
def create_all():
    from common.models.user import User  
    db.create_all()

manager.add_command("create_all", create_all)

def main():
    manager.run()
    
if __name__ == "__main__":
    # app.run( host = "0.0.0.0" )
    
    try:
        import sys
        sys.exit( main() )
    except Exception as e:
        import traceback
        traceback.print_exc()

Run

http://localhost:Access 5000 and succeed when the next screen appears!


 ![flask_app_image.JPG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/545184/b64db0c9-64cf-0b1b-e7a8-9935f14b5008.jpeg)


## Source
 I uploaded the source to gitHub, so if you have time, please download it (https://github.com/shixujapan/flask_app) and play with it.
## What to do next

 * Create a simple CRUD app using Flask
 * Consider cooperation with Vue.js


Recommended Posts

I summarized the folder structure of Flask
I summarized 11 types of operating systems
I investigated the mechanism of flask-login!
[Python] Organize the basic structure of Flask apps (Aim for de-copying)
[Super basics of Python] I learned the basics of the basics, so I summarized it briefly.
I summarized how to change the boot parameters of GRUB and GRUB2
I checked the contents of docker volume
I tried the asynchronous server of Django 3.0
I didn't know the basics of Python
[Python] I personally summarized the basic grammar.
The Python project template I think of.
I read the implementation of golang channel
[I touched the Raspberry Pi (1)] I summarized the basic operations of Minecraft Pi Edition (2015.5.23 pre-release)
Extraction of synonyms using Word2Vec went well, so I summarized the analysis
I tried the pivot table function of pandas
I tried cluster analysis of the weather map
I read the implementation of range (Objects / rangeobject.c)
I solved the deepest problem of Hiroshi Yuki.
I touched Flask
I tried Flask with Remote-Containers of VS Code
I summarized one year of self-taught data science.
I checked the list of shortcut keys of Jupyter
I tried to touch the API of ebay
I tried to correct the keystone of the image
Try the free version of Progate [Python I]
I checked the session retention period of django
I checked the processing speed of numpy one-dimensionalization
I touched some of the new features of Python 3.8 ①
I read and implemented the Variants of UKR
I want to customize the appearance of zabbix
I tried using the image filter of OpenCV
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
Calculate volume from the two-dimensional structure of a compound
I want to grep the execution result of strace
I tried the MNIST tutorial for beginners of tensorflow.
I followed the implementation of the du command (first half)
I compared the identity of the images by Hu moment
Maybe I overestimated the impact of ShellShock on CGI
Summarized the types of sum of squares for analysis of variance
I checked the output specifications of PyTorch's Bidirectional LSTM
I checked out the versions of Blender and Python
I want to fully understand the basics of Bokeh
The performance of PHP was better than I expected
I examined the argument class_weight of Chainer's softmax_cross_entropy function.
I measured the performance of 1 million documents with mongoDB
I checked the default OS and shell of docker-machine
I followed the implementation of the du command (second half)
I tried using the API of the salmon data project
I tried to visualize the spacha information of VTuber
I tried to erase the negative part of Meros
I tried scraping the advertisement of the pirated cartoon site
I investigated the reinforcement learning algorithm of algorithmic trading
I tried the simplest method of multi-label document classification
I tried to classify the voices of voice actors
I want to increase the security of ssh connections
I searched for the contents of CloudWatch Logs Agent
I tried running the sample code of the Ansible module
I tried to summarize the string operations of Python
The beginning of cif2cell
Folder structure for analysis