简单示例

2024-01-08  本文已影响0人  xueyueshuai

目录结构

run.py
dbConfig.py
controller/user.py
model/user.py

run.py

from flask import Flask

from dbConfig import db
import dbConfig

from controller.user import user_blueprint
from controller.article import article_blueprint

# 实力化app
app = Flask(__name__)
app.config.from_object(dbConfig)

# db部分
db.app = app
db.init_app(app)

# 注册蓝图
app.register_blueprint(user_blueprint)
app.register_blueprint(article_blueprint)


if __name__ == '__main__':
    app.run()

dbConfig.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1:3306/test1?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = False

model/user.py

from dbConfig import db


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

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    age = db.Column(db.Integer())


controller/user

from flask import Blueprint
from dbConfig import db
from model.user import User

user_blueprint = Blueprint('user', __name__)


@user_blueprint.route('/user/add', methods=['get', 'post'])
def user_add():
    user = User(name='a', age=11)
    db.session.add(user)
    db.session.commit()
    return '用户-add success'


@user_blueprint.route('/user/delete')
def user_del():
    # user = User.query.filter(User.id == 2).first()
    user = User.query.get(3)
    db.session.delete(user)
    db.session.commit()
    return '用户-delete success'


@user_blueprint.route('/user/update')
def user_update():
    user = User.query.get(1)
    user.name = user.name + 'a'
    db.session.commit()
    return '用户-update success'


@user_blueprint.route('/user/list')
def user_list():
    users = User.query.all()
    user_arr = []

    for user in users:
        user_arr.append({
            'id': user.id,
            'name': user.name,
            'age': user.age
        })
    return user_arr


@user_blueprint.route('/user/info')
def user_info():
    # user = User.query.filter(User.id == 2).first()
    user = User.query.get(2)

    user_dict = {
        'id': user.id,
        'name': user.name,
        'age': user.age
    }
    return user_dict
上一篇下一篇

猜你喜欢

热点阅读