《zdppy_aocrud官方教程》 03 自动生成根据条件查询的接口
这个方法非常的灵活,在真实的开发中,你只需要关注数据应该怎么查询即可,接口该怎么编写则不用关心。
这个方法非常适合定制化的复杂的查询场景,比如:
import aocrud
import env
import orm
from api import Api, resp
env.load("../.env")
db, BaseModel = orm.get_mysql_pool_base_model_by_env()
class User(BaseModel):
name = orm.CharField()
age = orm.IntegerField()
path, method = aocrud.method.get_condition(
"user",
condition=User.select().where(User.id > 10),
)
app = Api(routes=[
resp.get(path, method),
])
if __name__ == "__main__":
import uvicorn
uvicorn.run("server:app", port=8000)
import req
r = req.get("http://127.0.0.1:8000/user_condition")
print(r.json())
import aocrud
import env
import orm
from api import Api, resp
env.load("../.env")
db, BaseModel = orm.get_mysql_pool_base_model_by_env()
class User(BaseModel):
name = orm.CharField()
age = orm.IntegerField()
def handle_queries(queries):
"""
处理前端传递过来的查询参数
:param queries: 前端传递过来的查询参数,是一个字典
:return: 要求返回一个列表或者字典
"""
page = queries.get("page", 1)
size = queries.get("size", 20)
data = list(User.select().where(User.id > 1).paginate(int(page), int(size)).dicts())
return data
path, method = aocrud.method.get_condition(
"user",
condition_func=handle_queries,
)
app = Api(routes=[
resp.get(path, method),
])
if __name__ == "__main__":
import uvicorn
uvicorn.run("server:app", port=8000)
import req
# 默认:page=1 size=20
r = req.get("http://127.0.0.1:8000/user_condition")
print(r.json())
# page=2 size=2
r = req.get("http://127.0.0.1:8000/user_condition?page=2&size=2")
print(r.json())
import aocrud
import env
import orm
from api import Api
env.load("../.env")
db, BaseModel = orm.get_mysql_pool_base_model_by_env()
class User(BaseModel):
name = orm.CharField()
age = orm.IntegerField()
app = Api(routes=[
aocrud.route.get_condition_route(
"user",
condition=User.select().where(User.id > 15),
),
])
if __name__ == "__main__":
import uvicorn
uvicorn.run("server:app", port=8000)
import aocrud
import env
import orm
from api import Api
env.load("../.env")
db, BaseModel = orm.get_mysql_pool_base_model_by_env()
class User(BaseModel):
name = orm.CharField()
age = orm.IntegerField()
def handle_queries(queries):
"""
处理前端传递过来的查询参数
:param queries: 前端传递过来的查询参数,是一个字典
:return: 要求返回一个列表或者字典
"""
page = queries.get("page", 1)
size = queries.get("size", 20)
data = list(User.select().where(User.id > 1).paginate(int(page), int(size)).dicts())
return data
app = Api(routes=[
aocrud.route.get_condition_route("user", condition_func=handle_queries),
])
if __name__ == "__main__":
import uvicorn
uvicorn.run("server:app", port=8000)
import req
r = req.get("http://127.0.0.1:8000/user_condition")
print(r.json())