32 lines
1008 B
Python
32 lines
1008 B
Python
from sqlalchemy import *
|
|||
|
|
from sqlalchemy.orm import declarative_base, sessionmaker
|
||
|
|
|
||
|
|
db_url = "mysql+pymysql://root:123456@127.0.0.1:3306/ai0824?charset=utf8mb4"
|
||
|
|
engine = create_engine(db_url)
|
||
|
|
|
||
|
|
Base = declarative_base()
|
||
|
|
Session = sessionmaker(bind=engine
|
||
|
|
, autoflush=False
|
||
|
|
, autocommit=False
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def get_db():
|
||
|
|
db = Session()
|
||
|
|
try:
|
||
|
|
yield db
|
||
|
|
finally:
|
||
|
|
db.close()
|
||
|
|
|
||
|
|
@order_api.put('/{id}')
|
||
|
|
def get_orders(order:OrderRequest,id:int,db=Depends(get_db)):
|
||
|
|
try: # 数据更新是有返回值的,返回的是影响的行数
|
||
|
|
rows = db.query( Order ).filter( Order.id == id ).update( order.model_dump(exclude_unset=True) )
|
||
|
|
except:
|
||
|
|
db.rollback()
|
||
|
|
raise HTTPException(status_code=500, detail='更新异常,请稍后执行!')
|
||
|
|
else:
|
||
|
|
db.commit()
|
||
|
|
print('更新影响的行数:',rows)
|
||
|
|
return {'code':200,'totals':rows,'detail':'更新成功'}
|