defupdate_user(user_id:int,**kwargs)-> Optional[User]:with Session(engine)as session:
user = session.get(User, user_id)ifnot user:returnNone# 更新提供的字段for key, value in kwargs.items():ifhasattr(user, key):setattr(user, key, value)try:
session.add(user)
session.commit()
session.refresh(user)return user
except Exception as e:
session.rollback()raise e
# 使用示例
updated_user = update_user(1, email="newemail@example.com", is_active=False)
3.4 删除操作 (Delete)
defdelete_user(user_id:int)->bool:with Session(engine)as session:
user = session.get(User, user_id)ifnot user:returnFalsetry:
session.delete(user)
session.commit()returnTrueexcept Exception as e:
session.rollback()raise e
defbulk_create_users(users_data:list[dict])->list[User]:with Session(engine)as session:try:
users =[User(**data)for data in users_data]
session.add_all(users)
session.commit()for user in users:
session.refresh(user)return users
except Exception as e:
session.rollback()raise e
4.3 异步操作
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
# 异步数据库URL
ASYNC_DATABASE_URL ="postgresql+asyncpg://user:password@localhost/dbname"
async_engine = create_async_engine(ASYNC_DATABASE_URL)asyncdefasync_get_user(user_id:int)-> Optional[User]:asyncwith AsyncSession(async_engine)as session:
statement = select(User).where(User.id== user_id)
result =await session.exec(statement)return result.first()
from sqlalchemy.exc import IntegrityError, OperationalError
defsafe_create_user(username:str, email:str)->tuple[Optional[User],str]:try:
user = create_user(username, email)return user,"Success"except IntegrityError:returnNone,"User with this email already exists"except OperationalError:returnNone,"Database connection error"except Exception as e:returnNone,f"Unexpected error: {str(e)}"
5.3 模型验证
from pydantic import EmailStr, validator
classUserCreate(SQLModel):
username:str
email: EmailStr
@validator('username')defusername_must_be_valid(cls, v):iflen(v)<3:raise ValueError('Username must be at least 3 characters long')return v
【论文阅读】MedCLIP: Contrastive Learning from Unpaired Medical Images and Text 1.论文背景与动机2.MedCLIP的贡献3.提出的方法4.构建语义相似矩阵的过程5. 实验6. 结论与局限性 论文地址:
pdf github地址:项目地址
Zifeng Wang, Zhenbang Wu, Di…
大家觉得有有参考意义和帮助记得及时关注和点赞!!! Service mesh 是近两年网络、容器编排和微服务领域最火热的话题之一。Envoy 是目前 service mesh 数据平面的首选组件。Matt Klein 是 Envoy 的设计者和核心开发。
文章循序渐进࿰…