0.0.4
This commit is contained in:
@@ -16,7 +16,7 @@ class Shop(Model):
|
||||
shop_number (CharField): 店铺号码,最大长度 255, nullable 为 True
|
||||
"""
|
||||
id = fields.UUIDField(pk=True, default=uuid.uuid4, description="ID")
|
||||
province = fields.CharField(max_length=255, index=True, description="省份")
|
||||
province = fields.CharField(max_length=255, null=True, index=True, description="省份")
|
||||
city = fields.CharField(max_length=255, index=True, description="城市")
|
||||
street = fields.CharField(max_length=255, index=True, description="街道")
|
||||
shop_name = fields.CharField(max_length=255, index=True, description="店铺名称")
|
||||
|
||||
@@ -13,7 +13,7 @@ class Base(BaseModel):
|
||||
|
||||
包含店铺相关的通用字段,供创建与输出模型复用
|
||||
"""
|
||||
province: str = Field(..., description='省份')
|
||||
province: str | None = Field(None, description='省份')
|
||||
city: str = Field(..., description='城市')
|
||||
street: str = Field(..., description='街道')
|
||||
shop_name: str = Field(..., description='店铺名称')
|
||||
|
||||
@@ -6,6 +6,8 @@ from ..models import Shop
|
||||
from utils.decorators import handle_exceptions_unified
|
||||
from utils.time_tool import parse_time
|
||||
from utils.out_base import CommonOut
|
||||
from tortoise.transactions import in_transaction
|
||||
import random
|
||||
|
||||
app = APIRouter()
|
||||
|
||||
@@ -17,6 +19,9 @@ async def post(item: Create = Body(..., description='创建数据')):
|
||||
"""
|
||||
创建店铺记录
|
||||
"""
|
||||
res = await Shop.filter(street=item.street).first()
|
||||
if res:
|
||||
raise HTTPException(status_code=400, detail='店铺已存在')
|
||||
res = await Shop.create(**item.model_dump())
|
||||
if not res:
|
||||
raise HTTPException(status_code=400, detail='创建失败')
|
||||
@@ -132,3 +137,19 @@ async def delete(id: UUID = Query(..., description='主键ID'),
|
||||
# Tortoise ORM 单个实例的 delete() 方法返回 None,而不是删除的记录数
|
||||
# 删除成功时手动返回 1,如果有异常会被装饰器捕获
|
||||
return CommonOut(count=1)
|
||||
|
||||
# 随机取一个店铺
|
||||
@app.get("/random", response_model=Out, description='随机取一个店铺', summary='随机取一个店铺')
|
||||
@handle_exceptions_unified()
|
||||
async def get_random_shop():
|
||||
"""
|
||||
随机取一个店铺(事务内计数与偏移选择,避免数据库不稳定的随机排序)
|
||||
"""
|
||||
async with in_transaction() as conn:
|
||||
q = Shop.all().using_db(conn)
|
||||
total = await q.count()
|
||||
if total == 0:
|
||||
raise HTTPException(status_code=404, detail='店铺不存在')
|
||||
pick_index = random.choice(range(total))
|
||||
item = await q.order_by('create_time').offset(pick_index).first()
|
||||
return item
|
||||
Reference in New Issue
Block a user