Skip to content

Commit c685c02

Browse files
Merge pull request #5 from software-architecture-fiap/bugfix/trigger-deploy
Deploy in production
2 parents 091376b + 361b86e commit c685c02

File tree

1 file changed

+38
-12
lines changed

1 file changed

+38
-12
lines changed

app/main.py

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55
from fastapi.security import OAuth2PasswordBearer
66
from fastapi.middleware.cors import CORSMiddleware
77
from fastapi.openapi.docs import get_redoc_html
8-
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, HTTP_500_INTERNAL_SERVER_ERROR
8+
from starlette.status import (
9+
HTTP_422_UNPROCESSABLE_ENTITY,
10+
HTTP_500_INTERNAL_SERVER_ERROR,
11+
)
912
from contextlib import asynccontextmanager
13+
from fastapi.responses import HTMLResponse
1014

1115
from .middleware.middleware import ExceptionLoggingMiddleware
1216
from .routers import auth, customer
@@ -15,10 +19,13 @@
1519
from .database.database import Base, SessionLocal, engine
1620

1721
Base.metadata.create_all(bind=engine)
22+
23+
1824
def init_admin_user() -> None:
1925
"""Inicializa o usuário admin e configura o banco de dados.
2026
21-
Cria um usuário administrador e inicializa o banco de dados com dados padrão.
27+
Cria um usuário administrador e inicializa o banco de dados com dados
28+
padrão.
2229
2330
Returns:
2431
None
@@ -28,7 +35,8 @@ def init_admin_user() -> None:
2835
create_admin_user(db)
2936
finally:
3037
db.close()
31-
38+
39+
3240
@asynccontextmanager
3341
async def lifespan(app: FastAPI):
3442
"""Executa tarefas antes de iniciar a API"""
@@ -63,39 +71,52 @@ async def lifespan(app: FastAPI):
6371
app.include_router(auth.router, tags=['authentication'])
6472
app.include_router(customer.router, prefix='/customers', tags=['customers'])
6573

74+
75+
STATUS_CODE = "status code"
76+
77+
6678
@app.exception_handler(RequestValidationError)
6779
async def validation_exception_handler(request, exc):
6880
logger.error(f"Validation error: {exc}")
6981
return JSONResponse(
7082
status_code=HTTP_422_UNPROCESSABLE_ENTITY,
7183
content={
72-
"status code": 422,
73-
"msg": f"Validation error in request body or parameters: {exc.errors()}"
84+
STATUS_CODE: 422,
85+
"msg": (
86+
f"Validation error in request body or parameters: "
87+
f"{exc.errors()}"
88+
)
7489
},
7590
)
7691

92+
7793
@app.exception_handler(HTTPException)
7894
async def http_exception_handler(request, exc):
7995
logger.error(f"HTTP error: {exc.detail}")
8096
return JSONResponse(
8197
status_code=exc.status_code,
8298
content={
83-
"status code": exc.status_code,
99+
STATUS_CODE: exc.status_code,
84100
"msg": exc.detail,
85101
},
86102
)
87103

104+
88105
@app.exception_handler(Exception)
89106
async def global_exception_handler(request, exc):
90107
logger.error(f"Unexpected server error: {str(exc)}", exc_info=True)
91108
return JSONResponse(
92109
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
93110
content={
94-
"status code": 500,
95-
"msg": "An unexpected error occurred. Please try again later or contact your Support Team."
111+
STATUS_CODE: 500,
112+
"msg": """
113+
An unexpected error occurred.
114+
Please try again later or contact your Support Team.
115+
"""
96116
},
97117
)
98118

119+
99120
@app.get('/health', tags=['health'])
100121
def health_check() -> dict:
101122
"""Retorna o status operacional da aplicação.
@@ -106,26 +127,31 @@ def health_check() -> dict:
106127
logger.debug('Status endpoint accessed')
107128
return {'status': 'Operational'}
108129

109-
# Adiciona a rota para a documentação do ReDoc
130+
110131
@app.get('/redoc', include_in_schema=False, tags=['documentation'])
111-
async def redoc() -> str:
132+
async def redoc() -> HTMLResponse:
112133
"""Retorna o HTML para a documentação do ReDoc.
113134
114135
Returns:
115-
str: O HTML da documentação do ReDoc.
136+
HTMLResponse: O HTML da documentação do ReDoc.
116137
"""
117138
return get_redoc_html(
118139
openapi_url=app.openapi_url,
119140
title=app.title + ' - ReDoc',
120-
redoc_js_url='https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js',
141+
redoc_js_url=(
142+
'https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js'
143+
),
121144
)
122145

146+
123147
@app.get('/docs', tags=['documentation'])
124148
def get_docs():
125149
return app.openapi()
126150

151+
127152
def run_server():
128153
uvicorn.run("app.main:app", host="127.0.0.1", port=8000, reload=True)
129154

155+
130156
if __name__ == '__main__':
131157
run_server()

0 commit comments

Comments
 (0)