Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 5173ff7

Browse files
authoredSep 27, 2023
Update the global unified response code (#223)
* Update the global unified response * Update the uniform return model default * Update the environment variable type
1 parent 46d6fbc commit 5173ff7

File tree

7 files changed

+210
-79
lines changed

7 files changed

+210
-79
lines changed
 

‎backend/app/api/v1/mixed/tests.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ async def task_demo_add():
2424
task_demo, 'interval', seconds=1, id='task_demo', replace_existing=True, start_date=datetime.datetime.now()
2525
)
2626

27-
return await response_base.success({'msg': 'success'})
27+
return await response_base.success()
2828

2929

3030
@router.post('/async', summary='测试添加异步任务')
@@ -37,7 +37,7 @@ async def task_demo_add_async():
3737
replace_existing=True,
3838
start_date=datetime.datetime.now(),
3939
)
40-
return await response_base.success({'msg': 'success'})
40+
return await response_base.success()
4141

4242

4343
@router.post('/files', summary='测试文件上传')

‎backend/app/common/exception/errors.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
3+
"""
4+
全局业务异常类
5+
6+
业务代码执行异常时,可以使用 raise xxxError 触发内部错误,它尽可能实现带有后台任务的异常,但它不适用于**自定义响应状态码**
7+
如果要求使用**自定义响应状态码**,则可以通过 return await response_base.fail(res=CustomResponseCode.xxx) 直接返回
8+
""" # noqa: E501
39
from typing import Any
410

511
from fastapi import HTTPException
612
from starlette.background import BackgroundTask
713

8-
from backend.app.common.response.response_code import CustomCode
14+
from backend.app.common.response.response_code import CustomErrorCode, StandardResponseCode
915

1016

1117
class BaseExceptionMixin(Exception):
@@ -24,34 +30,34 @@ def __init__(self, *, code: int, msg: Any = None, headers: dict[str, Any] | None
2430

2531

2632
class CustomError(BaseExceptionMixin):
27-
def __init__(self, *, error: CustomCode, data: Any = None, background: BackgroundTask | None = None):
33+
def __init__(self, *, error: CustomErrorCode, data: Any = None, background: BackgroundTask | None = None):
2834
self.code = error.code
2935
super().__init__(msg=error.msg, data=data, background=background)
3036

3137

3238
class RequestError(BaseExceptionMixin):
33-
code = 400
39+
code = StandardResponseCode.HTTP_400
3440

3541
def __init__(self, *, msg: str = 'Bad Request', data: Any = None, background: BackgroundTask | None = None):
3642
super().__init__(msg=msg, data=data, background=background)
3743

3844

3945
class ForbiddenError(BaseExceptionMixin):
40-
code = 403
46+
code = StandardResponseCode.HTTP_403
4147

4248
def __init__(self, *, msg: str = 'Forbidden', data: Any = None, background: BackgroundTask | None = None):
4349
super().__init__(msg=msg, data=data, background=background)
4450

4551

4652
class NotFoundError(BaseExceptionMixin):
47-
code = 404
53+
code = StandardResponseCode.HTTP_404
4854

4955
def __init__(self, *, msg: str = 'Not Found', data: Any = None, background: BackgroundTask | None = None):
5056
super().__init__(msg=msg, data=data, background=background)
5157

5258

5359
class ServerError(BaseExceptionMixin):
54-
code = 500
60+
code = StandardResponseCode.HTTP_500
5561

5662
def __init__(
5763
self, *, msg: str = 'Internal Server Error', data: Any = None, background: BackgroundTask | None = None
@@ -60,21 +66,21 @@ def __init__(
6066

6167

6268
class GatewayError(BaseExceptionMixin):
63-
code = 502
69+
code = StandardResponseCode.HTTP_502
6470

6571
def __init__(self, *, msg: str = 'Bad Gateway', data: Any = None, background: BackgroundTask | None = None):
6672
super().__init__(msg=msg, data=data, background=background)
6773

6874

6975
class AuthorizationError(BaseExceptionMixin):
70-
code = 401
76+
code = StandardResponseCode.HTTP_401
7177

72-
def __init__(self, *, msg: str = 'Permission denied', data: Any = None, background: BackgroundTask | None = None):
78+
def __init__(self, *, msg: str = 'Permission Denied', data: Any = None, background: BackgroundTask | None = None):
7379
super().__init__(msg=msg, data=data, background=background)
7480

7581

7682
class TokenError(HTTPError):
77-
code = 401
83+
code = StandardResponseCode.HTTP_401
7884

79-
def __init__(self, *, msg: str = 'Not authenticated', headers: dict[str, Any] | None = None):
85+
def __init__(self, *, msg: str = 'Not Authenticated', headers: dict[str, Any] | None = None):
8086
super().__init__(code=self.code, msg=msg, headers=headers or {'WWW-Authenticate': 'Bearer'})

‎backend/app/common/exception/exception_handler.py

Lines changed: 33 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -9,35 +9,14 @@
99
from starlette.exceptions import HTTPException
1010
from starlette.middleware.cors import CORSMiddleware
1111
from starlette.responses import JSONResponse
12-
from uvicorn.protocols.http.h11_impl import STATUS_PHRASES
1312

1413
from backend.app.common.exception.errors import BaseExceptionMixin
1514
from backend.app.common.log import log
16-
from backend.app.common.response.response_schema import response_base
15+
from backend.app.common.response.response_code import StandardResponseCode, CustomResponseCode
16+
from backend.app.common.response.response_schema import response_base, ResponseModel
1717
from backend.app.core.conf import settings
1818

1919

20-
def _get_exception_code(status_code):
21-
"""
22-
获取返回状态码, OpenAPI, Uvicorn... 可用状态码基于 RFC 定义, 详细代码见下方链接
23-
24-
`python 状态码标准支持 <https://github.com/python/cpython/blob/6e3cc72afeaee2532b4327776501eb8234ac787b/Lib/http
25-
/__init__.py#L7>`__
26-
27-
`IANA 状态码注册表 <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml>`__
28-
29-
:param status_code:
30-
:return:
31-
"""
32-
try:
33-
STATUS_PHRASES[status_code]
34-
except Exception:
35-
code = 400
36-
else:
37-
code = status_code
38-
return code
39-
40-
4120
def register_exception(app: FastAPI):
4221
@app.exception_handler(HTTPException)
4322
async def http_exception_handler(request: Request, exc: HTTPException):
@@ -48,11 +27,11 @@ async def http_exception_handler(request: Request, exc: HTTPException):
4827
:param exc:
4928
:return:
5029
"""
51-
content = {'code': exc.status_code, 'msg': exc.detail}
30+
content = ResponseModel(code=exc.status_code, msg=exc.detail).dict()
5231
request.state.__request_http_exception__ = content # 用于在中间件中获取异常信息
5332
return JSONResponse(
54-
status_code=_get_exception_code(exc.status_code),
55-
content=await response_base.fail(**content),
33+
status_code=StandardResponseCode.HTTP_400,
34+
content=content if settings.ENVIRONMENT == 'dev' else await response_base.fail(CustomResponseCode.HTTP_400),
5635
headers=exc.headers,
5736
)
5837

@@ -94,13 +73,16 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
9473
message += f'{data.get(field, field) if field != "__root__" else ""} {msg}' + '.'
9574
elif isinstance(raw_error.exc, json.JSONDecodeError):
9675
message += 'json解析失败'
97-
content = {
98-
'code': 422,
99-
'msg': '请求参数非法' if len(message) == 0 else f'请求参数非法: {message}',
100-
'data': {'errors': exc.errors()} if message == '' and settings.UVICORN_RELOAD is True else None,
101-
}
76+
content = ResponseModel(
77+
code=StandardResponseCode.HTTP_422,
78+
msg='请求参数非法' if len(message) == 0 else f'请求参数非法: {message}',
79+
data={'errors': exc.errors()} if message == '' else None,
80+
).dict()
10281
request.state.__request_validation_exception__ = content # 用于在中间件中获取异常信息
103-
return JSONResponse(status_code=422, content=await response_base.fail(**content))
82+
return JSONResponse(
83+
status_code=StandardResponseCode.HTTP_422,
84+
content=content if settings.ENVIRONMENT == 'dev' else await response_base.fail(CustomResponseCode.HTTP_422),
85+
)
10486

10587
@app.exception_handler(Exception)
10688
async def all_exception_handler(request: Request, exc: Exception):
@@ -113,24 +95,28 @@ async def all_exception_handler(request: Request, exc: Exception):
11395
"""
11496
if isinstance(exc, BaseExceptionMixin):
11597
return JSONResponse(
116-
status_code=_get_exception_code(exc.code),
117-
content=await response_base.fail(code=exc.code, msg=str(exc.msg), data=exc.data if exc.data else None),
98+
status_code=StandardResponseCode.HTTP_400,
99+
content=ResponseModel(
100+
code=exc.code,
101+
msg=str(exc.msg),
102+
data=exc.data if exc.data else None,
103+
).dict(),
118104
background=exc.background,
119105
)
120106

121107
elif isinstance(exc, AssertionError):
122108
return JSONResponse(
123-
status_code=500,
124-
content=await response_base.fail(
125-
code=500,
109+
status_code=StandardResponseCode.HTTP_500,
110+
content=ResponseModel(
111+
code=StandardResponseCode.HTTP_500,
126112
msg=','.join(exc.args)
127113
if exc.args
128114
else exc.__repr__()
129115
if not exc.__repr__().startswith('AssertionError()')
130116
else exc.__doc__,
131-
)
117+
).dict()
132118
if settings.ENVIRONMENT == 'dev'
133-
else await response_base.fail(code=500, msg='Internal Server Error'),
119+
else await response_base.fail(CustomResponseCode.HTTP_500),
134120
)
135121

136122
else:
@@ -139,15 +125,15 @@ async def all_exception_handler(request: Request, exc: Exception):
139125
log.error(f'未知异常: {exc}')
140126
log.error(traceback.format_exc())
141127
return JSONResponse(
142-
status_code=500,
143-
content=await response_base.fail(code=500, msg=str(exc))
128+
status_code=StandardResponseCode.HTTP_500,
129+
content=ResponseModel(code=500, msg=str(exc)).dict()
144130
if settings.ENVIRONMENT == 'dev'
145-
else await response_base.fail(code=500, msg='Internal Server Error'),
131+
else await response_base.fail(StandardResponseCode.HTTP_500),
146132
)
147133

148134
if settings.MIDDLEWARE_CORS:
149135

150-
@app.exception_handler(500)
136+
@app.exception_handler(StandardResponseCode.HTTP_500)
151137
async def cors_status_code_500_exception_handler(request, exc):
152138
"""
153139
跨域 500 异常处理
@@ -159,12 +145,12 @@ async def cors_status_code_500_exception_handler(request, exc):
159145
:return:
160146
"""
161147
response = JSONResponse(
162-
status_code=exc.code if isinstance(exc, BaseExceptionMixin) else 500,
163-
content={'code': exc.code, 'msg': exc.msg, 'data': exc.data}
148+
status_code=exc.code if isinstance(exc, BaseExceptionMixin) else StandardResponseCode.HTTP_500,
149+
content=ResponseModel(code=exc.code, msg=exc.msg, data=exc.data).dict()
164150
if isinstance(exc, BaseExceptionMixin)
165-
else await response_base.fail(code=500, msg=str(exc))
151+
else ResponseModel(code=StandardResponseCode.HTTP_500, msg=str(exc)).dict()
166152
if settings.ENVIRONMENT == 'dev'
167-
else await response_base.fail(code=500, msg='Internal Server Error'),
153+
else await response_base.fail(CustomResponseCode.HTTP_500),
168154
background=exc.background if isinstance(exc, BaseExceptionMixin) else None,
169155
)
170156
origin = request.headers.get('origin')

‎backend/app/common/response/response_code.py

Lines changed: 131 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,146 @@
33
from enum import Enum
44

55

6-
class CustomCode(Enum):
7-
"""
8-
自定义错误码
9-
"""
10-
11-
CAPTCHA_ERROR = (40001, '验证码错误')
6+
class CustomCodeBase(Enum):
7+
"""自定义状态码基类"""
128

139
@property
1410
def code(self):
1511
"""
16-
获取错误码
12+
获取状态码
1713
"""
1814
return self.value[0]
1915

2016
@property
2117
def msg(self):
2218
"""
23-
获取错误码码信息
19+
获取状态码信息
2420
"""
2521
return self.value[1]
22+
23+
24+
class CustomResponseCode(CustomCodeBase):
25+
"""自定义响应状态码"""
26+
27+
HTTP_200 = (200, '请求成功')
28+
HTTP_201 = (201, '新建请求成功')
29+
HTTP_202 = (202, '请求已接受,但处理尚未完成')
30+
HTTP_204 = (204, '请求成功,但没有返回内容')
31+
HTTP_400 = (400, '请求错误')
32+
HTTP_401 = (401, '未经授权')
33+
HTTP_403 = (403, '禁止访问')
34+
HTTP_404 = (404, '请求的资源不存在')
35+
HTTP_410 = (410, '请求的资源已永久删除')
36+
HTTP_422 = (422, '请求参数非法')
37+
HTTP_425 = (425, '无法执行请求,由于服务器无法满足要求')
38+
HTTP_429 = (429, '请求过多,服务器限制')
39+
HTTP_500 = (500, '服务器内部错误')
40+
HTTP_502 = (502, '网关错误')
41+
HTTP_503 = (503, '服务器暂时无法处理请求')
42+
HTTP_504 = (504, '网关超时')
43+
44+
45+
class CustomErrorCode(CustomCodeBase):
46+
"""自定义错误状态码"""
47+
48+
CAPTCHA_ERROR = (40001, '验证码错误')
49+
50+
51+
class StandardResponseCode:
52+
"""标准响应状态码"""
53+
54+
"""
55+
HTTP codes
56+
See HTTP Status Code Registry:
57+
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
58+
59+
And RFC 2324 - https://tools.ietf.org/html/rfc2324
60+
"""
61+
HTTP_100 = 100 # CONTINUE: 继续
62+
HTTP_101 = 101 # SWITCHING_PROTOCOLS: 协议切换
63+
HTTP_102 = 102 # PROCESSING: 处理中
64+
HTTP_103 = 103 # EARLY_HINTS: 提示信息
65+
HTTP_200 = 200 # OK: 请求成功
66+
HTTP_201 = 201 # CREATED: 已创建
67+
HTTP_202 = 202 # ACCEPTED: 已接受
68+
HTTP_203 = 203 # NON_AUTHORITATIVE_INFORMATION: 非权威信息
69+
HTTP_204 = 204 # NO_CONTENT: 无内容
70+
HTTP_205 = 205 # RESET_CONTENT: 重置内容
71+
HTTP_206 = 206 # PARTIAL_CONTENT: 部分内容
72+
HTTP_207 = 207 # MULTI_STATUS: 多状态
73+
HTTP_208 = 208 # ALREADY_REPORTED: 已报告
74+
HTTP_226 = 226 # IM_USED: 使用了
75+
HTTP_300 = 300 # MULTIPLE_CHOICES: 多种选择
76+
HTTP_301 = 301 # MOVED_PERMANENTLY: 永久移动
77+
HTTP_302 = 302 # FOUND: 临时移动
78+
HTTP_303 = 303 # SEE_OTHER: 查看其他位置
79+
HTTP_304 = 304 # NOT_MODIFIED: 未修改
80+
HTTP_305 = 305 # USE_PROXY: 使用代理
81+
HTTP_307 = 307 # TEMPORARY_REDIRECT: 临时重定向
82+
HTTP_308 = 308 # PERMANENT_REDIRECT: 永久重定向
83+
HTTP_400 = 400 # BAD_REQUEST: 请求错误
84+
HTTP_401 = 401 # UNAUTHORIZED: 未授权
85+
HTTP_402 = 402 # PAYMENT_REQUIRED: 需要付款
86+
HTTP_403 = 403 # FORBIDDEN: 禁止访问
87+
HTTP_404 = 404 # NOT_FOUND: 未找到
88+
HTTP_405 = 405 # METHOD_NOT_ALLOWED: 方法不允许
89+
HTTP_406 = 406 # NOT_ACCEPTABLE: 不可接受
90+
HTTP_407 = 407 # PROXY_AUTHENTICATION_REQUIRED: 需要代理身份验证
91+
HTTP_408 = 408 # REQUEST_TIMEOUT: 请求超时
92+
HTTP_409 = 409 # CONFLICT: 冲突
93+
HTTP_410 = 410 # GONE: 已删除
94+
HTTP_411 = 411 # LENGTH_REQUIRED: 需要内容长度
95+
HTTP_412 = 412 # PRECONDITION_FAILED: 先决条件失败
96+
HTTP_413 = 413 # REQUEST_ENTITY_TOO_LARGE: 请求实体过大
97+
HTTP_414 = 414 # REQUEST_URI_TOO_LONG: 请求 URI 过长
98+
HTTP_415 = 415 # UNSUPPORTED_MEDIA_TYPE: 不支持的媒体类型
99+
HTTP_416 = 416 # REQUESTED_RANGE_NOT_SATISFIABLE: 请求范围不符合要求
100+
HTTP_417 = 417 # EXPECTATION_FAILED: 期望失败
101+
HTTP_418 = 418 # UNUSED: 闲置
102+
HTTP_421 = 421 # MISDIRECTED_REQUEST: 被错导的请求
103+
HTTP_422 = 422 # UNPROCESSABLE_CONTENT: 无法处理的实体
104+
HTTP_423 = 423 # LOCKED: 已锁定
105+
HTTP_424 = 424 # FAILED_DEPENDENCY: 依赖失败
106+
HTTP_425 = 425 # TOO_EARLY: 太早
107+
HTTP_426 = 426 # UPGRADE_REQUIRED: 需要升级
108+
HTTP_427 = 427 # UNASSIGNED: 未分配
109+
HTTP_428 = 428 # PRECONDITION_REQUIRED: 需要先决条件
110+
HTTP_429 = 429 # TOO_MANY_REQUESTS: 请求过多
111+
HTTP_430 = 430 # Unassigned: 未分配
112+
HTTP_431 = 431 # REQUEST_HEADER_FIELDS_TOO_LARGE: 请求头字段太大
113+
HTTP_451 = 451 # UNAVAILABLE_FOR_LEGAL_REASONS: 由于法律原因不可用
114+
HTTP_500 = 500 # INTERNAL_SERVER_ERROR: 服务器内部错误
115+
HTTP_501 = 501 # NOT_IMPLEMENTED: 未实现
116+
HTTP_502 = 502 # BAD_GATEWAY: 错误的网关
117+
HTTP_503 = 503 # SERVICE_UNAVAILABLE: 服务不可用
118+
HTTP_504 = 504 # GATEWAY_TIMEOUT: 网关超时
119+
HTTP_505 = 505 # HTTP_VERSION_NOT_SUPPORTED: HTTP 版本不支持
120+
HTTP_506 = 506 # VARIANT_ALSO_NEGOTIATES: 变体也会协商
121+
HTTP_507 = 507 # INSUFFICIENT_STORAGE: 存储空间不足
122+
HTTP_508 = 508 # LOOP_DETECTED: 检测到循环
123+
HTTP_509 = 509 # UNASSIGNED: 未分配
124+
HTTP_510 = 510 # NOT_EXTENDED: 未扩展
125+
HTTP_511 = 511 # NETWORK_AUTHENTICATION_REQUIRED: 需要网络身份验证
126+
127+
"""
128+
WebSocket codes
129+
https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
130+
https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
131+
"""
132+
WS_1000 = 1000 # NORMAL_CLOSURE: 正常闭合
133+
WS_1001 = 1001 # GOING_AWAY: 正在离开
134+
WS_1002 = 1002 # PROTOCOL_ERROR: 协议错误
135+
WS_1003 = 1003 # UNSUPPORTED_DATA: 不支持的数据类型
136+
WS_1005 = 1005 # NO_STATUS_RCVD: 没有接收到状态
137+
WS_1006 = 1006 # ABNORMAL_CLOSURE: 异常关闭
138+
WS_1007 = 1007 # INVALID_FRAME_PAYLOAD_DATA: 无效的帧负载数据
139+
WS_1008 = 1008 # POLICY_VIOLATION: 策略违规
140+
WS_1009 = 1009 # MESSAGE_TOO_BIG: 消息太大
141+
WS_1010 = 1010 # MANDATORY_EXT: 必需的扩展
142+
WS_1011 = 1011 # INTERNAL_ERROR: 内部错误
143+
WS_1012 = 1012 # SERVICE_RESTART: 服务重启
144+
WS_1013 = 1013 # TRY_AGAIN_LATER: 请稍后重试
145+
WS_1014 = 1014 # BAD_GATEWAY: 错误的网关
146+
WS_1015 = 1015 # TLS_HANDSHAKE: TLS握手错误
147+
WS_3000 = 3000 # UNAUTHORIZED: 未经授权
148+
WS_3003 = 3003 # FORBIDDEN: 禁止访问

‎backend/app/common/response/response_schema.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from pydantic import BaseModel
77

8+
from backend.app.common.response.response_code import CustomResponseCode
89
from backend.app.core.conf import settings
910
from backend.app.utils.encoders import jsonable_encoder
1011

@@ -31,10 +32,15 @@ def test():
3132
@router.get('/test')
3233
def test() -> ResponseModel:
3334
return ResponseModel(data={'test': 'test'})
35+
36+
@router.get('/test')
37+
def test() -> ResponseModel:
38+
res = CustomResponseCode.HTTP_200
39+
return ResponseModel(code=res.code, msg=res.msg, data={'test': 'test'})
3440
""" # noqa: E501
3541

36-
code: int = 200
37-
msg: str = 'Success'
42+
code: int = CustomResponseCode.HTTP_200.code
43+
msg: str = CustomResponseCode.HTTP_200.msg
3844
data: Any | None = None
3945

4046
class Config:
@@ -59,7 +65,7 @@ def test():
5965

6066
@staticmethod
6167
async def __response(
62-
*, code: int = None, msg: str = None, data: Any | None = None, exclude: _ExcludeData | None = None, **kwargs
68+
*, res: CustomResponseCode = None, data: Any | None = None, exclude: _ExcludeData | None = None, **kwargs
6369
) -> dict:
6470
"""
6571
请求成功返回通用方法
@@ -75,17 +81,27 @@ async def __response(
7581
custom_encoder = {datetime: lambda x: x.strftime(settings.DATETIME_FORMAT)}
7682
kwargs.update({'custom_encoder': custom_encoder})
7783
data = jsonable_encoder(data, exclude=exclude, **kwargs)
78-
return {'code': code, 'msg': msg, 'data': data}
84+
return {'code': res.code, 'msg': res.msg, 'data': data}
7985

8086
async def success(
81-
self, *, code=200, msg='Success', data: Any | None = None, exclude: _ExcludeData | None = None, **kwargs
87+
self,
88+
*,
89+
res: CustomResponseCode = CustomResponseCode.HTTP_200,
90+
data: Any | None = None,
91+
exclude: _ExcludeData | None = None,
92+
**kwargs
8293
) -> dict:
83-
return await self.__response(code=code, msg=msg, data=data, exclude=exclude, **kwargs)
94+
return await self.__response(res=res, data=data, exclude=exclude, **kwargs)
8495

8596
async def fail(
86-
self, *, code=400, msg='Bad Request', data: Any = None, exclude: _ExcludeData | None = None, **kwargs
97+
self,
98+
*,
99+
res: CustomResponseCode = CustomResponseCode.HTTP_400,
100+
data: Any = None,
101+
exclude: _ExcludeData | None = None,
102+
**kwargs
87103
) -> dict:
88-
return await self.__response(code=code, msg=msg, data=data, exclude=exclude, **kwargs)
104+
return await self.__response(res=res, data=data, exclude=exclude, **kwargs)
89105

90106

91107
response_base = ResponseBase()

‎backend/app/core/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
class Settings(BaseSettings):
1010
# Env Config
11-
ENVIRONMENT: str
11+
ENVIRONMENT: Literal['dev', 'pro']
1212

1313
# Env MySQL
1414
DB_HOST: str

‎backend/app/services/auth_service.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from backend.app.common.exception import errors
1313
from backend.app.common.jwt import get_token
1414
from backend.app.common.redis import redis_client
15-
from backend.app.common.response.response_code import CustomCode
15+
from backend.app.common.response.response_code import CustomErrorCode
1616
from backend.app.core.conf import settings
1717
from backend.app.crud.crud_user import UserDao
1818
from backend.app.database.db_mysql import async_db_session
@@ -55,7 +55,7 @@ async def login(self, *, request: Request, obj: AuthLogin, background_tasks: Bac
5555
if not captcha_code:
5656
raise errors.AuthorizationError(msg='验证码失效,请重新获取')
5757
if captcha_code.lower() != obj.captcha.lower():
58-
raise errors.CustomError(error=CustomCode.CAPTCHA_ERROR)
58+
raise errors.CustomError(error=CustomErrorCode.CAPTCHA_ERROR)
5959
await UserDao.update_login_time(db, obj.username, self.login_time)
6060
user = await UserDao.get(db, current_user.id)
6161
access_token, access_token_expire_time = await jwt.create_access_token(

0 commit comments

Comments
 (0)
Please sign in to comment.