Skip to content

Commit

Permalink
Fixed error with invalid pydantic model (added monkey patch the arbit…
Browse files Browse the repository at this point in the history
…rary class to tell fastapi a way to render it). See fastapi/fastapi#1186
  • Loading branch information
iduseev committed Oct 12, 2023
1 parent d6ed451 commit 7704d04
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 16 deletions.
20 changes: 16 additions & 4 deletions backend/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def recreate_required_indexes(self) -> None:
if self.logger:
self.logger.debug(
f"There are the following indexes {self.collection.name} within the collection: {', '.join(db_index_names_tuple)}"
)
)
# check that self.required_index_params value is valid, else return None
if not isinstance(self.required_index_params, list):
raise ValueError(
Expand All @@ -147,10 +147,11 @@ def recreate_required_indexes(self) -> None:
required_index_name, uniqueness_bool = required_index_data_piece
# check if need to restore absent index name
if required_index_name not in db_index_names_tuple:
if self.logger: self.logger.warning(
f"THe following index is required for the work: {required_index_name}, although it is absent in the collection. "
if self.logger:
self.logger.warning(
f"The following index is required for the work: {required_index_name}, although it is absent in the collection. "
f"Required index will be restored!"
)
)
self.collection.create_index(
[(required_index_name, pymongo.ASCENDING)],
unique=uniqueness_bool,
Expand Down Expand Up @@ -216,6 +217,17 @@ def read_first_match(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
return self.collection.find_one(data)

def extract_entire_collection(self) -> List[Dict]:
"""
Returns list of all existing documents from the
explicit collection by iterating over the cursor
:return: list of all documents from the collection
:rtype: List[Dict]
"""
cursor = self.collection.find()
return list(cursor)

def get_collection_names(self) -> List[AnyStr]:
"""
Gets a list of all the collection names in this database
Expand Down
27 changes: 16 additions & 11 deletions backend/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
# backend/endpoints.py

import sys
import traceback

from uuid import uuid4
from datetime import timedelta
from typing import Union, List, Dict, Annotated, NoReturn

from dotenv import dotenv_values
from pydantic import BaseConfig
from fastapi import FastAPI, Path, Body, Query, HTTPException, status, Request, Depends
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordRequestForm

# sys.path.append('utils')

from utils.logger_setup import logger_setup
from .database import MongoAdapter
from .security import create_access_token, get_password_hash
Expand All @@ -25,6 +29,10 @@
# initialize FastAPI application instance
app = FastAPI()

# to solve error "Response model with pydantic's arbitrary_types_allowed not working
# see https://github.com/tiangolo/fastapi/discussions/9043
BaseConfig.arbitrary_types_allowed = True

# init logger instance
logger = logger_setup()

Expand Down Expand Up @@ -119,7 +127,6 @@ async def login_for_access_token(
return Token(**access_token_data)


# fixme invalid Pydantic field type error is encountered during declaration of this endpoint
@app.get(
"/user/me",
summary="Information about current user",
Expand All @@ -138,8 +145,7 @@ async def read_user_me(
:rtype: User
"""
current_user_data = current_user.dict()
current_user_db_entry = UserInDB(**current_user_data)
return current_user_db_entry
return UserInDB(**current_user_data)


@app.post(
Expand Down Expand Up @@ -311,7 +317,7 @@ def show_books(
limit: int = Query(default=10, example=10)
) -> List[Book]:
"""
Shows all the books available on the book shelf, allows to limit the number of showed books
Shows all the books available on the book shelf, allows to limit the number of showed books
:param request: request object
:type request: Request
Expand All @@ -326,13 +332,12 @@ def show_books(
"Detected incoming GET request to /books endpoint from the"
"client with IP %s ...", client_host
)
# find and retrieve each book in the collection
cursor = ma_books_collection.find()
# convert the cursor to the list with Book models, considering the limit
all_books = []
for book_in_db in cursor:
book = Book(*book_in_db)
all_books.append(book)
# find and retrieve each document in the collection
all_books_in_db = ma_books_collection.extract_entire_collection()
# get the list with Book models, considering the limit
all_books = [
lambda book_in_db: Book(*book_in_db) for book_in_db in all_books_in_db
]
return all_books[: limit]


Expand Down
2 changes: 1 addition & 1 deletion backend/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from jose import jwt
from dotenv import dotenv_values
from passlib.context import CryptContext
from passlib.context import CryptContext


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
Expand Down

0 comments on commit 7704d04

Please sign in to comment.