Skip to content

Commit f35d0a3

Browse files
committed
feat: Add changes to use version 0.100.0 of FastAPI
This versión of FastAPI use the version 2 of Pydantic core rewritten in rust for a mayor efficiency (among other improvements) and implement minor changes for request error handling
1 parent d9e8fe8 commit f35d0a3

File tree

5 files changed

+34
-37
lines changed

5 files changed

+34
-37
lines changed

app/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from functools import lru_cache
2-
from pydantic import BaseSettings
2+
from pydantic_settings import BaseSettings
33

44

55
class Settings(BaseSettings):

app/controllers/graph_controller.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,8 @@ async def get_graph(repository_id: str) -> JSONResponse:
2020
2121
- **repository_id**: the id of a repository
2222
'''
23-
try:
24-
graph = await read_graph_by_repository_id(repository_id, '_')
25-
return JSONResponse(status_code=status.HTTP_200_OK, content=graph)
26-
except HTTPException as error:
27-
return JSONResponse(status_code=error.status_code, content=json_encoder({'message': error.detail}))
23+
graph = await read_graph_by_repository_id(repository_id, '_')
24+
return JSONResponse(status_code=status.HTTP_200_OK, content=graph)
2825

2926

3027
@router.post(
@@ -39,13 +36,10 @@ async def init_graph(repository: RepositoryModel) -> JSONResponse:
3936
- **repository**: a json containing the owner and the name of a repository
4037
'''
4138
repository_json = jsonable_encoder(repository)
42-
try:
43-
repository_id = await read_repository_by_owner_name(repository_json['owner'], repository_json['name'], '_')
44-
if not repository_id:
45-
await extract_graph(repository_json)
46-
else:
47-
# TODO: Hacer un método que actualize el grafo existente en la base de datos
48-
pass
49-
return JSONResponse(status_code=status.HTTP_201_CREATED, content=json_encoder({'message': 'created'}))
50-
except HTTPException as error:
51-
return JSONResponse(status_code=error.status_code, content=json_encoder({'message': error.detail}))
39+
repository_id = await read_repository_by_owner_name(repository_json['owner'], repository_json['name'], '_')
40+
if not repository_id:
41+
await extract_graph(repository_json)
42+
else:
43+
# TODO: Hacer un método que actualize el grafo existente en la base de datos
44+
pass
45+
return JSONResponse(status_code=status.HTTP_201_CREATED, content=json_encoder({'message': 'created'}))

app/main.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1-
from json import loads
21
from fastapi import FastAPI, Request
3-
from fastapi.exceptions import RequestValidationError, ValidationError
2+
from fastapi.exceptions import RequestValidationError
3+
from fastapi.exception_handlers import (
4+
http_exception_handler,
5+
request_validation_exception_handler,
6+
)
47
from starlette.middleware.cors import CORSMiddleware
5-
from starlette.responses import JSONResponse
8+
from starlette.exceptions import HTTPException
9+
from starlette.responses import Response
610
from apscheduler.schedulers.background import BackgroundScheduler
711
from app.controllers import db_updater
812
from app.router import api_router
913
from app.services import create_indexes
10-
from app.utils import json_encoder
1114

1215
DESCRIPTION = '''
1316
A backend for dependency graph building, atribution of vulnerabilities and reasoning
@@ -39,15 +42,14 @@ async def startup_event() -> None:
3942
scheduler.start()
4043

4144

45+
@app.exception_handler(HTTPException)
46+
async def custom_http_exception_handler(request: Request, exc: HTTPException) -> Response:
47+
return await http_exception_handler(request, exc)
48+
49+
4250
@app.exception_handler(RequestValidationError)
43-
@app.exception_handler(ValidationError)
44-
async def validation_exception_handler(_: Request, exc: ValidationError | RequestValidationError) -> JSONResponse:
45-
exc_json = loads(exc.json())
46-
response: dict[str, list[str]] = {'message': []}
47-
for error in exc_json:
48-
response['message'].append(error['loc'][-1] + f": {error['msg']}")
49-
50-
return JSONResponse(content=json_encoder(response), status_code=422)
51+
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> Response:
52+
return await request_validation_exception_handler(request, exc)
5153

5254
app.add_middleware(
5355
CORSMiddleware,

app/models/models.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ class VersionModel(BaseModel):
1616
count: int
1717

1818
class Config:
19-
allow_population_by_field_name = True
19+
populate_by_name = True
2020
arbitrary_types_allowed = True
21-
schema_extra = {
21+
json_schema_extra = {
2222
'example': {
2323
'release': '1.26.5',
2424
'release_date': datetime.now(),
@@ -34,9 +34,9 @@ class PackageModel(BaseModel):
3434
versions: list[VersionModel] | None
3535

3636
class Config:
37-
allow_population_by_field_name = True
37+
populate_by_name = True
3838
arbitrary_types_allowed = True
39-
schema_extra = {
39+
json_schema_extra = {
4040
'example': {
4141
'name': 'urllib3',
4242
'moment': datetime.now()
@@ -49,9 +49,9 @@ class RequirementFile(BaseModel):
4949
manager: str
5050

5151
class Config:
52-
allow_population_by_field_name = True
52+
populate_by_name = True
5353
arbitrary_types_allowed = True
54-
schema_extra = {
54+
json_schema_extra = {
5555
'example': {
5656
'name': 'requirements.txt',
5757
'manager': 'PIP'
@@ -75,9 +75,9 @@ class RepositoryModel(BaseModel):
7575
requirement_files: list[RequirementFile] | None
7676

7777
class Config:
78-
allow_population_by_field_name = True
78+
populate_by_name = True
7979
arbitrary_types_allowed = True
80-
schema_extra = {
80+
json_schema_extra = {
8181
'example': {
8282
'owner': 'depexorg',
8383
'name': 'pip_test',

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
wheel==0.40.0
2-
fastapi[all]==0.98.0
2+
fastapi[all]==0.100.0
3+
pydantic-settings==2.0.1
34
apscheduler==3.10.1
45
motor==3.1.2
56
python-dotenv==1.0.0

0 commit comments

Comments
 (0)