学习日志flask01flasksqlalchemy文件组织结构示例

32次阅读

共计 3095 个字符,预计需要花费 8 分钟才能阅读完成。

1 用意

flask 灵活的文件组织结构让很多新手玩家痛苦万分, 网上的相关教程也是良莠不齐, 本人也是在几近崩溃的边缘疯狂试探
, 坚持即时胜利, 终于被我摸索出一个较为适用的简单文件组织结构. 本文从单文件结构, 逐步拆分成多个部分, 至于其中
各个步骤拆分的用意, 还请恕在下才疏学浅, 难以用文字形容, 各位看官请自行体会.

2. 简单示例

目录结构

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..'
HOST = '127.0.0.1'
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> 首页 </title>
</head>
<body>
    <a href="/sign_up"> 注册 </a>
</body>
</html>

sign_up.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 注册 </title>
</head>
<body>
    <form action="/sign_up" method="post">
        <label for="name"> 用户名 </label><input type="text" name="name" id="name">
        <label for="content"> 密 码 </label><input type="text" name="content" id="content">
        <input type="submit" value="提交">
    </form>
</body>
</html>

2. 开始拆分

首先我们在根目录中新建一个 extensions.py, 将app.py 中的头部部分拿进去
extensions.py


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

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

然后在根目录中新建 models 包, 并在 models 里面新建 record.py 文件
record.py

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)

接着在根目录下新建 routes 包, 并在 routes 里面新建 record.py 的路由文件


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'))

最后在根目录中新建一个入口文件run.py

run.py


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

    app.run()

目录结构

数据库初始化比较简单, 请自行建库建表, 修改连接配置
自此大功告成, 迈过 flask 的第一大坑

正文完
 0