diff --git a/Teachers/api/tea_api.py b/Teachers/api/tea_api.py index 26715bb..7d86fc8 100644 --- a/Teachers/api/tea_api.py +++ b/Teachers/api/tea_api.py @@ -28,13 +28,17 @@ def delete_tea(id:int|None,db=Depends(get_db)): raise HTTPException(status_code=500,detail='删除失败!') return {'detail':'删除成功!'} -@tea_api.put('/tea/{id}',summary='更新老师信息',description='输入更改的信息,可以为空') -def update_tea(id:int,tea:NewTeaRequest,db=Depends(get_db)): - t = tea.model_dump(exclude_unset= True) - r = update_tea_dao(id=id,t=t,db=db) - if not r: - raise HTTPException(status_code=404,detail='老师不存在') - return {'detail':'更新成功'} +@tea_api.put('/tea/{id}', summary='更新老师信息', description='输入更改的信息,可以为空') +def update_tea(id: int, tea: NewTeaRequest = Depends(), db=Depends(get_db)): + t = tea.model_dump(exclude_unset=True) + r = update_tea_dao(id=id, t=t, db=db) + if r == 'NOT_FOUND': + raise HTTPException(status_code=404, detail='老师不存在') + if r == 'NO_CHANGE': + raise HTTPException(status_code=400, detail='没有要更新的内容') + if isinstance(r, str) and r.startswith('ERROR'): + raise HTTPException(status_code=400, detail=r) + return {'detail': '更新成功'} #根据任意信息删除 @tea_api.delete('/tea',summary='根据任意信息逻辑删除',description='输入任意信息删除') diff --git a/Teachers/dao/tea_dao.py b/Teachers/dao/tea_dao.py index 1820930..655bc9d 100644 --- a/Teachers/dao/tea_dao.py +++ b/Teachers/dao/tea_dao.py @@ -29,15 +29,22 @@ def add_tea_dao(t,db): #更新 -def update_tea_dao(id,t, db): +def update_tea_dao(id, t, db): try: - row = db.query(Tea).filter(Tea.id == id,Tea.is_delete ==False ).update(t) - except: - db.rollback() - return False - else: + if not t: + return 'NO_CHANGE' + obj = db.query(Tea).filter(Tea.id == id, Tea.is_delete == False).first() + if not obj: + return 'NOT_FOUND' + for k, v in t.items(): + if hasattr(obj, k): + setattr(obj, k, v) db.commit() - return row + return 'OK' + except Exception as e: + db.rollback() + print('更新失败原因', repr(e)) + return f'ERROR: {e}' #查询 def get_tea_dao(t,db): diff --git a/Teachers/main.py b/Teachers/main.py index bd87a8d..cb1251b 100644 --- a/Teachers/main.py +++ b/Teachers/main.py @@ -15,7 +15,7 @@ if __name__ == "__main__": Base.metadata.create_all(engine1) import uvicorn - uvicorn.run('main:app', host='0.0.0.0', port=57000) + uvicorn.run('main:app', host='0.0.0.0', port=56000) """ IPv4 地址 . . . . . . . . . . . . : 192.168.1.51 子网掩码 . . . . . . . . . . . . : 255.255.255.0