1 the intention

Flask’s flexible file organization structure makes many novice players very painful, and the relevant tutorials on the Internet are also uneven. I am also on the verge of collapse crazy test, insist on instant victory, and finally I find out a more suitable simple file organization structure. This article from the single file structure, gradually split into many parts, as for the intention of each step split, also please forgive in the next talent and lack of knowledge, it is difficult to use words to describe, you see the official please experience.

2. Simple examples

The directory structure

app.py

from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) class Record(db.Model): __tablename__ = 'record' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) @app.route('/') def index(): return render_template('index.html') @app.route('/sign_up', methods=['GET', 'POST']) def add_user(): if request.method == 'GET': return render_template('sign_up.html') else: for i in request.args: print(i) # print(request.args.get('username')) #None name = request.form.get('name') print("name={}".format(name)) content = request.form.get('content') print("content={}".format(content)) record = Record(name=name, content=content) db.session.add(record) db.session.commit() return redirect(url_for('index')) if __name__ == '__main__':  db.init_app(app) app.run()

config.py

SQLALCHEMY_TRACK_MODIFICATIONS=True DIALECT = 'mysql' DRIVER = 'pymysql' USERNAME = 'root' PASSWORD = 'hujin666.. = '127.0.0.1' 'HOST PORT =' 3306 'DATABASE =' socketio_test 'SQLALCHEMY_DATABASE_URI = "{} + {} : / / {}, {} @ {}, {} / {}? charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)

index.html

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset=" utf-8 "> <title> </head> <body> <a href="/sign_up"> </a> </body> </html>

sign_up.html

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset=" utf-8 "> <title> </head> <body> <form action="/sign_up" Method ="post"> <label for="name"> </label><input type="text" name="name" id="name"> <label for="content"> Code < / label > < input type = "text" name = "content" id = "content" > < input type = "submit" value = "submit" > < / form > < / body > < / HTML >

2. Start splitting

To start, create a new extension. py in the root directory and put the header from app.py in extension. py


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)

Then create a new Models package in the root directory and a new Record.py file within Models

from extensions import db
class Record(db.Model):
    __tablename__ = 'record'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)

Then create a new Routes package in the root directory and a new route file for Record.py inside Routes


from extensions import app,db
from flask import render_template, request, redirect, url_for
from models.record import Record


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/sign_up', methods=['GET', 'POST'])
def add_user():
    if request.method == 'GET':
        return render_template('sign_up.html')
    else:
        for i in request.args:
            print(i)
        # print(request.args.get('username')) #None
        name = request.form.get('name')
        print("name={}".format(name))
        content = request.form.get('content')
        print("content={}".format(content))
        record = Record(name=name, content=content)
        db.session.add(record)
        db.session.commit()
        return redirect(url_for('index'))

Finally, create a new entry file, run.py, in the root directory

run.py


from extensions import db
from routes.record import app
if __name__ == '__main__':
    db.init_app(app)

    app.run()

The directory structure

Database initialization is relatively simple, please build your own database to build a table, modify the connection configuration from this is done, over the first pit flask