Skip to content

Commit 2a2e923

Browse files
authored
Print-errors update. (#53)
## Изменения Добавлены русские описания ошибок, возникающих при попытке печати файла. ## Реализации В хэндлеры добавлены новые поля с русским описанием ошибок. ## Детали В каждый хэндлер, в возвращаемый JSON добавлено поле 'ru', содержащее русское описание ошибки. ## Check-List - [x] Вы проверили свой код перед отправкой запроса? - [x] Вы написали тесты к реализованным функциям? - **НЕ ТРЕБУЕТСЯ** - [x] Вы не забыли применить black и isort? ***P.S. Проставьте x в квадратные скобки в нужных пунктах. Example: [x]***
1 parent bf61f49 commit 2a2e923

File tree

3 files changed

+91
-24
lines changed

3 files changed

+91
-24
lines changed

print_service/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@ class Config:
1515
class StatusResponseModel(Base):
1616
status: str
1717
message: str
18+
ru: str
Lines changed: 75 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import requests.models
12
import starlette.requests
23
from starlette.responses import JSONResponse
34

@@ -22,126 +23,183 @@
2223
UserNotFound,
2324
)
2425
from print_service.routes.base import app
26+
from print_service.settings import get_settings
27+
28+
29+
settings = get_settings()
2530

2631

2732
@app.exception_handler(TooLargeSize)
2833
async def too_large_size(req: starlette.requests.Request, exc: TooLargeSize):
2934
return JSONResponse(
30-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=413
35+
content=StatusResponseModel(
36+
status="Error",
37+
message=f"{exc}",
38+
ru=f"Размер файла превышает максимально допустимый: {settings.MAX_SIZE}",
39+
).dict(),
40+
status_code=413,
3141
)
3242

3343

3444
@app.exception_handler(TooManyPages)
3545
async def too_many_pages(req: starlette.requests.Request, exc: TooManyPages):
3646
return JSONResponse(
37-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=413
47+
content=StatusResponseModel(
48+
status="Error",
49+
message=f"{exc}",
50+
ru=f"Количество запрошенных страниц превышает допустимое число: {settings.MAX_PAGE_COUNT}",
51+
).dict(),
52+
status_code=413,
3853
)
3954

4055

4156
@app.exception_handler(InvalidPageRequest)
4257
async def invalid_format(req: starlette.requests.Request, exc: TooManyPages):
4358
return JSONResponse(
44-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=416
59+
content=StatusResponseModel(
60+
status="Error",
61+
message=f"{exc}",
62+
ru="Количество запрошенных страниц превышает их количество в файле",
63+
).dict(),
64+
status_code=416,
4565
)
4666

4767

4868
@app.exception_handler(TerminalQRNotFound)
4969
async def terminal_not_found_by_qr(req: starlette.requests.Request, exc: TerminalQRNotFound):
5070
return JSONResponse(
51-
content=StatusResponseModel(status="Error", message=f"Terminal not found by QR").dict(),
71+
content=StatusResponseModel(
72+
status="Error", message="Terminal not found by QR", ru="QR-код не найден"
73+
).dict(),
5274
status_code=400,
5375
)
5476

5577

5678
@app.exception_handler(TerminalTokenNotFound)
5779
async def terminal_not_found_by_token(req: starlette.requests.Request, exc: TerminalTokenNotFound):
5880
return JSONResponse(
59-
content=StatusResponseModel(status="Error", message=f"Terminal not found by token").dict(),
81+
content=StatusResponseModel(
82+
status="Error", message="Terminal not found by token", ru="Токен не найден"
83+
).dict(),
6084
status_code=400,
6185
)
6286

6387

6488
@app.exception_handler(UserNotFound)
6589
async def user_not_found(req: starlette.requests.Request, exc: UserNotFound):
6690
return JSONResponse(
67-
content=StatusResponseModel(status="Error", message=f"User not found").dict(), status_code=404
91+
content=StatusResponseModel(
92+
status="Error", message="User not found", ru="Пользователь не найден"
93+
).dict(),
94+
status_code=404,
6895
)
6996

7097

7198
@app.exception_handler(UnionStudentDuplicate)
7299
async def student_duplicate(req: starlette.requests.Request, exc: UnionStudentDuplicate):
73100
return JSONResponse(
74-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=400
101+
content=StatusResponseModel(
102+
status="Error",
103+
message=f"{exc}",
104+
ru="Один или более пользователей в списке не являются уникальными",
105+
).dict(),
106+
status_code=400,
75107
)
76108

77109

78110
@app.exception_handler(NotInUnion)
79111
async def not_in_union(req: starlette.requests.Request, exc: NotInUnion):
80112
return JSONResponse(
81-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=403
113+
content=StatusResponseModel(
114+
status="Error",
115+
message=f"{exc}",
116+
ru="Отсутствует членство в профсоюзе",
117+
).dict(),
118+
status_code=403,
82119
)
83120

84121

85122
@app.exception_handler(PINGenerateError)
86123
async def generate_error(req: starlette.requests.Request, exc: PINGenerateError):
87124
return JSONResponse(
88-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=500
125+
content=StatusResponseModel(
126+
status="Error",
127+
message=f"{exc}",
128+
ru="Ошибка генерации ПИН-кода",
129+
).dict(),
130+
status_code=500,
89131
)
90132

91133

92134
@app.exception_handler(FileIsNotReceived)
93135
async def file_not_received(req: starlette.requests.Request, exc: FileIsNotReceived):
94136
return JSONResponse(
95-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=400
137+
content=StatusResponseModel(status="Error", message=f"{exc}", ru="Файл не получен").dict(),
138+
status_code=400,
96139
)
97140

98141

99142
@app.exception_handler(PINNotFound)
100143
async def pin_not_found(req: starlette.requests.Request, exc: PINNotFound):
101144
return JSONResponse(
102-
content=StatusResponseModel(status="Error", message=f"Pin {exc.pin} not found").dict(),
145+
content=StatusResponseModel(
146+
status="Error", message=f"Pin {exc.pin} not found", ru="ПИН не найден"
147+
).dict(),
103148
status_code=404,
104149
)
105150

106151

107152
@app.exception_handler(InvalidType)
108153
async def invalid_type(req: starlette.requests.Request, exc: InvalidType):
109154
return JSONResponse(
110-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=415
155+
content=StatusResponseModel(
156+
status="Error",
157+
message=f"{exc}",
158+
ru=f"Неподдерживаемый формат файла. Допустимые: {', '.join(settings.CONTENT_TYPES)}",
159+
).dict(),
160+
status_code=415,
111161
)
112162

113163

114164
@app.exception_handler(AlreadyUploaded)
115165
async def already_upload(req: starlette.requests.Request, exc: AlreadyUploaded):
116166
return JSONResponse(
117-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=415
167+
content=StatusResponseModel(status="Error", message=f"{exc}", ru="Файл уже загружен").dict(),
168+
status_code=415,
118169
)
119170

120171

121172
@app.exception_handler(IsCorrupted)
122173
async def is_corrupted(req: starlette.requests.Request, exc: IsCorrupted):
123174
return JSONResponse(
124-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=415
175+
content=StatusResponseModel(status="Error", message=f"{exc}", ru="Файл повреждён").dict(),
176+
status_code=415,
125177
)
126178

127179

128180
@app.exception_handler(UnprocessableFileInstance)
129181
async def unprocessable_file_instance(req: starlette.requests.Request, exc: UnprocessableFileInstance):
130182
return JSONResponse(
131-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=422
183+
content=StatusResponseModel(
184+
status="Error", message=f"{exc}", ru="Необрабатываемый экземпляр файла"
185+
).dict(),
186+
status_code=422,
132187
)
133188

134189

135190
@app.exception_handler(FileNotFound)
136191
async def file_not_found(req: starlette.requests.Request, exc: FileNotFound):
137192
return JSONResponse(
138-
content=StatusResponseModel(status="Error", message=f"{exc.count} file(s) not found").dict(),
193+
content=StatusResponseModel(
194+
status="Error", message=f"{exc.count} file(s) not found", ru="Файл не найден"
195+
).dict(),
139196
status_code=404,
140197
)
141198

142199

143200
@app.exception_handler(IsNotUploaded)
144201
async def not_uploaded(req: starlette.requests.Request, exc: IsNotUploaded):
145202
return JSONResponse(
146-
content=StatusResponseModel(status="Error", message=f"{exc}").dict(), status_code=415
203+
content=StatusResponseModel(status="Error", message=f"{exc}", ru="Файл не загружен").dict(),
204+
status_code=415,
147205
)

print_service/routes/file.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from pydantic import Field, validator
1212
from sqlalchemy import func, or_
1313

14+
from print_service.base import StatusResponseModel
1415
from print_service.exceptions import (
1516
AlreadyUploaded,
1617
FileIsNotReceived,
@@ -100,7 +101,8 @@ class ReceiveOutput(BaseModel):
100101
@router.post(
101102
'',
102103
responses={
103-
403: {'detail': 'User error'},
104+
403: {'model': StatusResponseModel, 'detail': 'User error'},
105+
500: {'model': StatusResponseModel, 'detail': 'PIN generate error'},
104106
},
105107
response_model=SendOutput,
106108
)
@@ -124,7 +126,7 @@ async def send(inp: SendInput, settings: Settings = Depends(get_settings)):
124126
try:
125127
pin = generate_pin(db.session)
126128
except RuntimeError:
127-
raise PINGenerateError
129+
raise PINGenerateError()
128130
filename = generate_filename(inp.filename)
129131
file_model = FileModel(pin=pin, file=filename)
130132
file_model.owner = user
@@ -147,8 +149,11 @@ async def send(inp: SendInput, settings: Settings = Depends(get_settings)):
147149
@router.post(
148150
'/{pin:str}',
149151
responses={
150-
404: {'detail': 'Pin not found'},
151-
415: {'detail': 'File error'},
152+
400: {'model': StatusResponseModel, 'detail': 'File is not received'},
153+
404: {'model': StatusResponseModel, 'detail': 'Pin not found'},
154+
415: {'model': StatusResponseModel, 'detail': 'File error'},
155+
413: {'model': StatusResponseModel, 'detail': 'Too large file'},
156+
416: {'model': StatusResponseModel, 'detail': 'Invalid page request'},
152157
},
153158
response_model=SendOutput,
154159
)
@@ -216,7 +221,9 @@ async def upload_file(
216221
@router.patch(
217222
'/{pin:str}',
218223
responses={
219-
404: {'detail': 'Pin not found'},
224+
404: {'model': StatusResponseModel, 'detail': 'Pin not found'},
225+
413: {'model': StatusResponseModel, 'detail': 'Too many pages'},
226+
416: {'model': StatusResponseModel, 'detail': 'Invalid page request'},
220227
},
221228
response_model=SendOutput,
222229
)
@@ -261,8 +268,9 @@ async def update_file_options(
261268
@router.get(
262269
'/{pin:str}',
263270
responses={
264-
404: {'detail': 'Pin not found'},
265-
415: {'detail': 'File error'},
271+
404: {'model': StatusResponseModel, 'detail': 'Pin not found'},
272+
415: {'model': StatusResponseModel, 'detail': 'File error'},
273+
416: {'model': StatusResponseModel, 'detail': 'Invalid page request'},
266274
},
267275
response_model=ReceiveOutput,
268276
)

0 commit comments

Comments
 (0)