Skip to content

Commit

Permalink
feat: Add changes to use version 0.100.0 of FastAPI
Browse files Browse the repository at this point in the history
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
  • Loading branch information
GermanMT committed Jul 9, 2023
1 parent f3e4068 commit db79b30
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 74 deletions.
2 changes: 1 addition & 1 deletion app/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from functools import lru_cache

from pydantic import BaseSettings
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
Expand Down
69 changes: 24 additions & 45 deletions app/controllers/student_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,13 @@
@router.post('/student', response_description='Create student', response_model=StudentModel)
async def create_student_data(student: StudentModel) -> JSONResponse:
student_json = jsonable_encoder(student)
try:
new_student = await create_student(student_json)
return JSONResponse(
status_code=status.HTTP_201_CREATED,
content=json_encoder(new_student)
)
except HTTPException as error:
return JSONResponse(
status_code=error.status_code,
content=json_encoder({'message': error.detail}))
if student_json['age'] == 3:
raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
new_student = await create_student(student_json)
return JSONResponse(
status_code=status.HTTP_201_CREATED,
content=json_encoder(new_student)
)


@router.get(
Expand All @@ -38,17 +35,11 @@ async def create_student_data(student: StudentModel) -> JSONResponse:
response_model=StudentModel
)
async def read_student_data(student_id: str) -> JSONResponse:
try:
student = await read_student(student_id)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=json_encoder(student)
)
except HTTPException as error:
return JSONResponse(
status_code=error.status_code,
content=json_encoder({'message': error.detail})
)
student = await read_student(student_id)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=json_encoder(student)
)


@router.put(
Expand All @@ -58,19 +49,13 @@ async def read_student_data(student_id: str) -> JSONResponse:
)
async def update_student_data(student_id: str, student: StudentModel) -> JSONResponse:
student_json = jsonable_encoder(student)
try:
await update_student(student_id, student_json)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=json_encoder(
{'message': f'Student with id {student_id} updated successfully'}
)
)
except HTTPException as error:
return JSONResponse(
status_code=error.status_code,
content=json_encoder({'message': error.detail})
await update_student(student_id, student_json)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=json_encoder(
{'message': f'Student with id {student_id} updated successfully'}
)
)


@router.delete(
Expand All @@ -79,16 +64,10 @@ async def update_student_data(student_id: str, student: StudentModel) -> JSONRes
response_model=dict[str, str]
)
async def delete_student_data(student_id: str) -> JSONResponse:
try:
await delete_student(student_id)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=json_encoder(
{'message': f'Student with id {student_id} deleted successfully'}
)
await delete_student(student_id)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=json_encoder(
{'message': f'Student with id {student_id} deleted successfully'}
)
except HTTPException as error:
return JSONResponse(
status_code=error.status_code,
content=json_encoder({'message': error.detail})
)
)
43 changes: 18 additions & 25 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,32 @@
from json import loads

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError, ValidationError

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.exception_handlers import (
http_exception_handler,
request_validation_exception_handler,
)
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse

from starlette.exceptions import HTTPException
from app.router import api_router

from app.services.populate_service import students_bulkwrite

from app.utils.json_encoder import json_encoder

DESCRIPTION = '''
A simple template for python projects using FastAPI and MongoDB
## Documentation
Related documentation and links about this template.
[FastAPI](https://fastapi.tiangolo.com/)
[FastAPI](https://fastapi.tiangolo.com/): A modern, fast (high-performance), web framework for building APIs with Python
[Pydantic](https://pydantic-docs.helpmanual.io/)
[Pydantic](https://pydantic-docs.helpmanual.io/): Data validation library for Python.
[Motor](https://motor.readthedocs.io/en/stable/): Asynchronous Python driver for MongoDB
[Motor](https://motor.readthedocs.io/en/stable/): Asynchronous Python driver for MongoDB.
'''

app = FastAPI(
title="FastAPI/MongoDB Template",
description=DESCRIPTION,
version="1.3.0",
version="1.4.0",
contact={
"name": "Antonio Germán Márquez Trujillo",
"url": "https://github.com/GermanMT",
Expand All @@ -38,18 +35,14 @@
)


@app.exception_handler(HTTPException)
async def custom_http_exception_handler(request, exc):
return await http_exception_handler(request, exc)


@app.exception_handler(RequestValidationError)
@app.exception_handler(ValidationError)
async def validation_exception_handler(
_: Request,
exc: ValidationError | RequestValidationError
) -> JSONResponse:
exc_json = loads(exc.json())
response: dict[str, list[str]] = {'message': []}
for error in exc_json:
response['message'].append(error['loc'][-1] + f": {error['msg']}")

return JSONResponse(content=json_encoder(response), status_code=422)
async def validation_exception_handler(request, exc):
return await request_validation_exception_handler(request, exc)


@app.on_event("startup")
Expand Down
4 changes: 2 additions & 2 deletions app/models/student_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def phone_validation(cls, phone: str) -> ValueError | str:
return phone

class Config:
allow_population_by_field_name = True
populate_by_name = True
arbitrary_types_allowed = True
schema_extra = {
json_schema_extra = {
'example': {
'name': 'John',
'surname': 'Doe',
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
wheel==0.40.0
fastapi[all]==0.98.0
fastapi[all]==0.100.0
pydantic-settings==2.0.1
motor==3.2.0
python-dotenv==1.0.0
requests==2.31.0

0 comments on commit db79b30

Please sign in to comment.