美文网首页
2023-12-08

2023-12-08

作者: xueyueshuai | 来源:发表于2023-12-07 14:02 被阅读0次

    /model/user_model.py

    
    from flask import Blueprint
    
    from model.base_model import Session
    from model.user_model import User
    
    user_blueprint = Blueprint('user', __name__)
    
    
    @user_blueprint.route('/user/add')
    def user_add():
        user = User(name='a', age=1)
    
        session = Session()
        session.add(user)
        session.commit()
        return '用户-add'
    
    
    @user_blueprint.route('/user/del')
    def user_del():
        session = Session()
        user = session.query(User).get(1)
    
        session.delete(user)
        session.commit()
        return '用户-del'
    
    
    @user_blueprint.route('/user/update')
    def user_update():
        session = Session()
        user = session.query(User).get(2)
        user.age = 22
        session.commit()
        return '用户-update'
    
    
    @user_blueprint.route('/user/list')
    def user_list():
        session = Session()
        res = session.query(User).all()
    
        rows = []
        for item in res:
            row = {}
            for k, v in item.__dict__.items():
                if k != '_sa_instance_state':
                    row[k] = v
            rows.append(row)
        return rows
    
    
    @user_blueprint.route('/user/info')
    def user_info():
        session = Session()
        res = session.query(User).get(2)
    
        user_dict = res.__dict__
        del user_dict['_sa_instance_state']
    
        return user_dict
    
    

    /model/base_model.py

    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker, scoped_session
    
    # 创建数据库连接
    db_host = 'xxx.xxx.xxx.xxx'
    db_user = 'xys-test'
    db_pass = 'xys-test'
    db_database = 'xys-test'
    
    engine = create_engine('mysql+pymysql://%s:%s@%s:3306/%s' % (db_user, db_pass, db_host, db_database))
    
    # 创建 scoped session
    Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
    
    # 创建基础模型
    Base = declarative_base()
    

    相关文章

      网友评论

          本文标题:2023-12-08

          本文链接:https://www.haomeiwen.com/subject/tqisgdtx.html