|
| 1 | +from http import HTTPStatus |
| 2 | +from typing import ( |
| 3 | + List, |
| 4 | + Union, |
| 5 | +) |
| 6 | + |
| 7 | +from fastapi import Depends |
| 8 | +from sqlalchemy import select, desc |
| 9 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 10 | +from tortoise.exceptions import DoesNotExist |
| 11 | +from tortoise.queryset import QuerySet |
| 12 | + |
| 13 | +from examples.api_for_sqlalchemy.extensions.sqlalchemy import Connector |
| 14 | +from examples.api_for_sqlalchemy.helpers.factories.meta_base import FactoryUseMode |
| 15 | +from examples.api_for_sqlalchemy.helpers.factories.user import UserFactory, ErrorCreateUserObject |
| 16 | +from examples.api_for_sqlalchemy.helpers.updaters.exceptions import ObjectNotFound |
| 17 | +from examples.api_for_sqlalchemy.helpers.updaters.update_user import UpdateUser, ErrorUpdateUserObject |
| 18 | +from examples.api_for_sqlalchemy.models.pydantic import UserSchema, UserPatchSchema |
| 19 | +from examples.api_for_sqlalchemy.models.pydantic.user import UserInSchema |
| 20 | +from examples.api_for_sqlalchemy.models.sqlalchemy import User |
| 21 | +from fastapi_rest_jsonapi import SqlalchemyEngine |
| 22 | + |
| 23 | +from fastapi_rest_jsonapi.exceptions import ( |
| 24 | + BadRequest, |
| 25 | + HTTPException, |
| 26 | +) |
| 27 | +from fastapi_rest_jsonapi.querystring import QueryStringManager |
| 28 | +from fastapi_rest_jsonapi.schema import JSONAPIResultListSchema |
| 29 | + |
| 30 | + |
| 31 | +class UserDetail: |
| 32 | + @classmethod |
| 33 | + async def get_user(cls, user_id, query_params: QueryStringManager, session: AsyncSession) -> User: |
| 34 | + """ |
| 35 | + Get user by id from ORM. |
| 36 | +
|
| 37 | + :param user_id: int |
| 38 | + :param query_params: QueryStringManager |
| 39 | + :return: User model. |
| 40 | + :raises HTTPException: if user not found. |
| 41 | + """ |
| 42 | + user: User |
| 43 | + try: |
| 44 | + user = (await session.execute(select(User).where(User.id == user_id))).scalar_one() |
| 45 | + except DoesNotExist: |
| 46 | + raise HTTPException( |
| 47 | + status_code=HTTPStatus.FORBIDDEN, |
| 48 | + detail="User with id {id} not found".format(id=user_id), |
| 49 | + ) |
| 50 | + |
| 51 | + return user |
| 52 | + |
| 53 | + @classmethod |
| 54 | + async def get(cls, obj_id, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 55 | + user: User = await cls.get_user(user_id=obj_id, query_params=query_params, session=session) |
| 56 | + return UserSchema.from_orm(user) |
| 57 | + |
| 58 | + @classmethod |
| 59 | + async def patch(cls, obj_id, data: UserPatchSchema, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 60 | + user_obj: User |
| 61 | + try: |
| 62 | + user_obj = await UpdateUser.update( |
| 63 | + obj_id, |
| 64 | + data.dict(exclude_unset=True), |
| 65 | + query_params.headers, |
| 66 | + session=session, |
| 67 | + ) |
| 68 | + except ErrorUpdateUserObject as ex: |
| 69 | + raise BadRequest(ex.description, ex.field) |
| 70 | + except ObjectNotFound as ex: |
| 71 | + raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail=ex.description) |
| 72 | + |
| 73 | + user = UserSchema.from_orm(user_obj) |
| 74 | + return user |
| 75 | + |
| 76 | + |
| 77 | +class UserList: |
| 78 | + @classmethod |
| 79 | + async def get(cls, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> Union[QuerySet, JSONAPIResultListSchema]: |
| 80 | + user_query = select(User).order_by(desc(User.id)) |
| 81 | + dl = SqlalchemyEngine(query=user_query, schema=UserSchema, model=User, session=session) |
| 82 | + count, users_db = await dl.get_collection(qs=query_params) |
| 83 | + total_pages = count // query_params.pagination.size + (count % query_params.pagination.size and 1) |
| 84 | + users: List[UserSchema] = [UserSchema.from_orm(i_user) for i_user in users_db] |
| 85 | + return JSONAPIResultListSchema( |
| 86 | + meta={"count": count, "totalPages": total_pages}, |
| 87 | + data=[{"id": i_obj.id, "attributes": i_obj.dict(), "type": "user"} for i_obj in users], |
| 88 | + ) |
| 89 | + |
| 90 | + @classmethod |
| 91 | + async def post(cls, data: UserInSchema, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 92 | + try: |
| 93 | + user_obj = await UserFactory.create( |
| 94 | + data=data.dict(), |
| 95 | + mode=FactoryUseMode.production, |
| 96 | + header=query_params.headers, |
| 97 | + session=session, |
| 98 | + ) |
| 99 | + except ErrorCreateUserObject as ex: |
| 100 | + raise BadRequest(ex.description, ex.field) |
| 101 | + |
| 102 | + user = UserSchema.from_orm(user_obj) |
| 103 | + return user |
0 commit comments