重写封装类,规范路由以符合restful风格

This commit is contained in:
mxwj 2024-11-08 15:26:17 +08:00
parent 0a749ff31a
commit f58831a6d3
6 changed files with 87 additions and 103 deletions

@ -3,6 +3,7 @@ from fastapi.responses import JSONResponse
from src.financial_reports.schemas import * from src.financial_reports.schemas import *
from src.financial_reports.service import * from src.financial_reports.service import *
from src.responses import response_list_response
financial_reports_router = APIRouter() financial_reports_router = APIRouter()
@ -15,11 +16,12 @@ async def financial_repoets_query(request: FinancialReportQuery )-> JSONResponse
return result return result
@financial_reports_router.post("/keyword_search") @financial_reports_router.post("/keyword-search")
async def financial_repoets_query_keyword_search(query: SearchKeywordQuery) -> list: async def financial_repoets_query_keyword_search(query: SearchKeywordQuery) -> list:
""" """
模糊查询接口 模糊查询接口
""" """
result = await user_keyword_search_service(query.searchKeyword) result = await user_keyword_search_service(query.searchKeyword)
return result # 使用封装类返回列表响应
return response_list_response(data=result, message="联想词查询成功")

@ -1,5 +1,9 @@
from tortoise import fields, Model from tortoise import fields, Model
"""
待补全每日更新表的爬虫
"""
class StockHuShenJingA(Model): class StockHuShenJingA(Model):
""" """
沪深京 A 股实时行情数据 沪深京 A 股实时行情数据

@ -1,6 +1,5 @@
import typing import typing
from typing import Generic, Sequence, TypeVar from typing import Generic, Sequence, TypeVar
from fastapi import status from fastapi import status
from fastapi.encoders import jsonable_encoder from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
@ -8,61 +7,40 @@ from pydantic import BaseModel
T = TypeVar("T") T = TypeVar("T")
class BaseResponse(BaseModel, Generic[T]):
"""通用响应类"""
status_code: int
message: str
data: typing.Optional[T] = None
class EntityResponse(BaseModel, Generic[T]): def json_response(self) -> JSONResponse:
"""实体数据""" """返回 JSONResponse 响应"""
status_code: int = 200
message: str = "Success"
data: T
class ListResponse(BaseModel, Generic[T]):
"""列表数据"""
status_code: int = 200
message: str = "Success"
data: Sequence[T]
# 包装响应的 Pydantic 模型
# class EntityPageResponse(BaseModel, Generic[T]):
# status_code: int
# message: str
# data: PageData
def response_entity_response(data, status_code=200, message="Success") -> EntityResponse:
"""普通实体类"""
return EntityResponse(data=data, status_code=status_code, message=message)
# def response_page_response(data, status_code=200, message="Success") -> EntityPageResponse:
# """普通分页类"""
# return EntityPageResponse(data=data, status_code=status_code, message=message)
def response_list_response(data, status_code=200, message="Success") -> ListResponse:
"""普通列表数据"""
return ListResponse(data=data, status_code=status_code, message=message)
def response_success(message: str = 'Success',
headers: typing.Optional[typing.Dict[str, str]] = None) -> JSONResponse:
"""成功返回"""
return JSONResponse( return JSONResponse(
status_code=status.HTTP_200_OK, status_code=self.status_code,
headers=headers, content=jsonable_encoder(self.dict())
content=jsonable_encoder({ )
"status_code": status.HTTP_200_OK,
"message": message,
}))
def response_unauthorized() -> JSONResponse: def create_response(data: T = None, status_code: int = 200, message: str = "Success") -> JSONResponse:
"""未登录""" """通用响应函数"""
return JSONResponse( response = BaseResponse(status_code=status_code, message=message, data=data)
status_code=status.HTTP_401_UNAUTHORIZED, return response.json_response()
headers={"WWW-Authenticate": "Bearer"},
content=jsonable_encoder({
"status_code": status.HTTP_401_UNAUTHORIZED, # 使用示例
"message": '用户认证失败', def response_success(message: str = 'Success') -> JSONResponse:
})) return create_response(status_code=status.HTTP_200_OK, message=message)
def response_unauthorized(message: str = "用户认证失败") -> JSONResponse:
return create_response(status_code=status.HTTP_401_UNAUTHORIZED, message=message)
def response_entity_response(data: T, message: str = "Success") -> JSONResponse:
"""单个实体数据响应"""
return create_response(data=data, status_code=200, message=message)
def response_list_response(data: Sequence[T], message: str = "Success") -> JSONResponse:
"""列表数据响应"""
return create_response(data=data, status_code=200, message=message)

@ -3,7 +3,7 @@ from src.models.stock import Stock
async def generate_pinyin_abbreviation(): async def generate_pinyin_abbreviation():
""" """
更新数据库中所有股票记录的拼音缩写如果字段为空则生成并保存 更新数据库中所有股票记录的拼音缩写如果字段为空则生成并保存,待抽象为通用组件
""" """
stocks = await Stock.filter(stock_pinyin__isnull=True) # 查找拼音字段为空的记录 stocks = await Stock.filter(stock_pinyin__isnull=True) # 查找拼音字段为空的记录
for stock in stocks: for stock in stocks: