fastapi搭建平台实战教程四:使用已有数据库编写api接口

如果有能复用的数据库,通过sqlalchemy可以直接对一个数据库数据进行增删改查的操作。

1. main.py初始化数据库连接,并自动生成表对象。

...
engine = create_engine("mysql+pymysql://root:@localhost:3306/xxx?charset=utf8mb4", echo=True) session = Session(engine) user_model = Table('eb_user', MetaData(), autoload_with=engine)

app = FastAPI()
...

某开源平台的用户表,很多字段用不到

create table eb_user
(
    uid                  int unsigned auto_increment comment '用户id'
        primary key,
    account              varchar(32)             default ''   not null comment '用户账号',
    pwd                  varchar(32)             default ''   not null comment '用户密码',
    real_name            varchar(25)             default ''   not null comment '真实姓名',
    birthday             int                     default 0    not null comment '生日',
    card_id              varchar(20)             default ''   not null comment '身份证号码',
    mark                 varchar(255)            default ''   not null comment '用户备注',
    partner_id           int                     default 0    not null comment '合伙人id',
    group_id             int                     default 0    not null comment '用户分组id',
    nickname             varchar(60)             default ''   not null comment '用户昵称',
    avatar               varchar(256)            default ''   not null comment '用户头像',
    phone                char(15)                default ''   not null comment '手机号码',
    add_time             int(11) unsigned        default 0    not null comment '添加时间',
    add_ip               varchar(16)             default ''   not null comment '添加ip',
    last_time            int(11) unsigned        default 0    not null comment '最后一次登录时间',
    last_ip              varchar(16)             default ''   not null comment '最后一次登录ip',
    now_money            decimal(12, 2) unsigned default 0.00 not null comment '用户余额',
    brokerage_price      decimal(12, 2)          default 0.00 not null comment '佣金金额',
    integral             int unsigned            default 0    not null comment '用户剩余积分',
    exp                  decimal(12, 2)          default 0.00 not null comment '会员经验',
    sign_num             int                     default 0    not null comment '连续签到天数',
    sign_remind          tinyint(1)              default 0    not null comment '签到提醒状态',
    status               tinyint(1)              default 1    not null comment '1为正常,0为禁止',
    level                tinyint(2) unsigned     default 0    not null comment '等级',
    agent_level          int(10)                 default 0    not null comment '分销等级',
    spread_open          tinyint(1)              default 1    not null comment '是否有推广资格',
    spread_uid           int unsigned            default 0    not null comment '推广元id',
    spread_time          int(11) unsigned        default 0    not null comment '推广员关联时间',
    user_type            varchar(32)             default ''   not null comment '用户类型',
    is_promoter          tinyint(1) unsigned     default 0    not null comment '是否为推广员',
    pay_count            int(11) unsigned        default 0    not null comment '用户购买次数',
    spread_count         int                     default 0    not null comment '下级人数',
    clean_time           int                     default 0    not null comment '清理会员时间',
    addres               varchar(255)            default ''   not null comment '详细地址',
    adminid              int(11) unsigned        default 0    not null comment '管理员编号 ',
    login_type           varchar(36)             default ''   not null comment '用户登陆类型,h5,wechat,routine',
    record_phone         varchar(11)             default '0'  not null comment '记录临时电话',
    is_money_level       tinyint(1)              default 0    not null comment '会员来源  0: 购买商品升级   1:花钱购买的会员2: 会员卡领取',
    is_ever_level        tinyint(1)              default 0    not null comment '是否永久性会员  0: 非永久会员  1:永久会员',
    overdue_time         bigint                  default 0    not null comment '会员到期时间',
    uniqid               varchar(32)             default ''   not null comment '用户唯一值',
    division_type        tinyint(1)              default 0    not null comment '代理类型:0普通,1事业部,2代理,3员工',
    division_status      tinyint(1)              default 0    not null comment '代理状态',
    is_division          tinyint(1)              default 0    not null comment '事业部状态',
    is_agent             tinyint(1)              default 0    not null comment '代理状态',
    is_staff             tinyint(1)              default 0    not null comment '员工状态',
    division_id          int                     default 0    not null comment '事业部id',
    agent_id             int                     default 0    not null comment '代理商id',
    staff_id             int                     default 0    not null comment '员工id',
    division_percent     int                     default 0    not null comment '分佣比例',
    division_change_time int                     default 0    not null comment '事业部/代理/员工修改时间',
    division_end_time    int                     default 0    not null comment '事业部/代理/员工结束时间',
    division_invite      int                     default 0    not null comment '代理商邀请码',
    is_del               tinyint(1)              default 0    not null comment '是否注销'
)
    comment '用户表' charset = utf8;

2. 编写接口直接增删改查数据

class UserBase(BaseModel):
    account: str
    pwd: str

@app.post("/user/save")
def user_save(user:UserBase):
    session.execute(insert(user_model).values(account=user.account,pwd=user.pwd))
    session.commit()
    return {"msg":"创建成功"}

class UserUserRes(BaseModel):
    account: str
    nickname: str
    phone: str

@app.get("/user/user",response_model=List[UserUserRes])
def user_user(page: int = 1,limit: int = 20,nickname: str = ""):
    data = session.query(user_model).filter(user_model.c.nickname.like(f"%{nickname}%")).offset(page).limit(limit).all()
    return data

@app.get("/user/user/{id}",response_model=UserUserRes)
def user_user(id: int):
    data = session.query(user_model).filter_by(uid=id).first()
    return data

@app.delete("/user/user/{id}")
def user_user(id: int):
    session.execute(update(user_model).where(user_model.c.uid==id).values(status=0))
    session.commit()
    return {"msg":"删除成功"}

3. 测试接口

 据此编写更多借口可以实现借尸还魂。

 

 

posted @ 2023-11-09 09:59  紧肛胡撸娃  阅读(260)  评论(0编辑  收藏  举报