add first commit
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import modelvault
|
||||
|
||||
from chongming_worker import rpc_method
|
||||
|
||||
from ..models.pydantic import CountGetResponse
|
||||
from ..models.counter import Counter
|
||||
|
||||
|
||||
@rpc_method(
|
||||
subject="example.count",
|
||||
method="GET",
|
||||
summary="Increment and get counter value",
|
||||
response_model=CountGetResponse, # 需要定义 CountResponse
|
||||
)
|
||||
async def count_get() -> CountGetResponse:
|
||||
from ..global_var import db
|
||||
|
||||
# 确保数据库已初始化(如果未初始化,则同步初始化,但这里假设已就绪)
|
||||
if db is None:
|
||||
raise RuntimeError("Database not initialized")
|
||||
|
||||
counters = modelvault.models.async_collection(db, Counter) # type: ignore
|
||||
async with db.transaction():
|
||||
counter = await counters.get("visits")
|
||||
if counter is None:
|
||||
counter = Counter(name="visits", value=0)
|
||||
await counters.insert(counter)
|
||||
else:
|
||||
new_value = counter.value + 1
|
||||
await counters.update("visits", {"value": new_value})
|
||||
counter.value = new_value # 更新本地对象以便返回
|
||||
|
||||
return CountGetResponse(name=counter.name, value=counter.value) # type: ignore
|
||||
Reference in New Issue
Block a user