|
| 1 | +.. _data_layer: |
| 2 | + |
| 3 | +Data layer |
| 4 | +========== |
| 5 | + |
| 6 | +.. currentmodule:: fastapi_jsonapi |
| 7 | + |
| 8 | +| The data layer is a CRUD interface between resource manager and data. It is a very flexible system to use any ORM or data storage. You can even create a data layer that uses multiple ORMs and data storage to manage your own objects. The data layer implements a CRUD interface for objects and relationships. It also manages pagination, filtering and sorting. |
| 9 | +| |
| 10 | +| FastAPI-JSONAPI has a full-featured data layer that uses the popular ORM `SQLAlchemy <https://www.sqlalchemy.org/>`_. |
| 11 | +
|
| 12 | +.. note:: |
| 13 | + |
| 14 | + The default data layer used by a resource manager is the SQLAlchemy one. So if that's what you want to use, you don't have to specify the class of the data layer in the resource manager |
| 15 | + |
| 16 | +To configure the data layer you have to set its required parameters in the resource manager. |
| 17 | + |
| 18 | +Example: |
| 19 | + |
| 20 | +.. code-block:: python |
| 21 | +
|
| 22 | + from http import HTTPStatus |
| 23 | + from typing import ( |
| 24 | + List, |
| 25 | + Union, |
| 26 | + ) |
| 27 | +
|
| 28 | + from fastapi import Depends |
| 29 | + from sqlalchemy import select, desc |
| 30 | + from sqlalchemy.ext.asyncio import AsyncSession |
| 31 | + from sqlalchemy.sql import Select |
| 32 | + from tortoise.exceptions import DoesNotExist |
| 33 | +
|
| 34 | + from examples.api_for_sqlalchemy.extensions.sqlalchemy import Connector |
| 35 | + from examples.api_for_sqlalchemy.helpers.factories.meta_base import FactoryUseMode |
| 36 | + from examples.api_for_sqlalchemy.helpers.factories.user import UserFactory, ErrorCreateUserObject |
| 37 | + from examples.api_for_sqlalchemy.helpers.updaters.exceptions import ObjectNotFound |
| 38 | + from examples.api_for_sqlalchemy.helpers.updaters.update_user import UpdateUser, ErrorUpdateUserObject |
| 39 | + from examples.api_for_sqlalchemy.models.pydantic import UserSchema, UserPatchSchema |
| 40 | + from examples.api_for_sqlalchemy.models.pydantic.user import UserInSchema |
| 41 | + from examples.api_for_sqlalchemy.models.sqlalchemy import User |
| 42 | + from fastapi_jsonapi import SqlalchemyEngine |
| 43 | + from fastapi_jsonapi.exceptions import ( |
| 44 | + BadRequest, |
| 45 | + HTTPException, |
| 46 | + ) |
| 47 | + from fastapi_jsonapi.querystring import QueryStringManager |
| 48 | + from fastapi_jsonapi.schema import JSONAPIResultListSchema |
| 49 | +
|
| 50 | +
|
| 51 | + class UserDetail: |
| 52 | + @classmethod |
| 53 | + async def get_user(cls, user_id, query_params: QueryStringManager, session: AsyncSession) -> User: |
| 54 | + """ |
| 55 | + Get user by id from ORM. |
| 56 | +
|
| 57 | + :param user_id: int |
| 58 | + :param query_params: QueryStringManager |
| 59 | + :return: User model. |
| 60 | + :raises HTTPException: if user not found. |
| 61 | + """ |
| 62 | + user: User |
| 63 | + try: |
| 64 | + user = (await session.execute(select(User).where(User.id == user_id))).scalar_one() |
| 65 | + except DoesNotExist: |
| 66 | + raise HTTPException( |
| 67 | + status_code=HTTPStatus.FORBIDDEN, |
| 68 | + detail="User with id {id} not found".format(id=user_id), |
| 69 | + ) |
| 70 | +
|
| 71 | + return user |
| 72 | +
|
| 73 | + @classmethod |
| 74 | + async def get(cls, obj_id, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 75 | + user: User = await cls.get_user(user_id=obj_id, query_params=query_params, session=session) |
| 76 | + return UserSchema.from_orm(user) |
| 77 | +
|
| 78 | + @classmethod |
| 79 | + async def patch(cls, obj_id, data: UserPatchSchema, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 80 | + user_obj: User |
| 81 | + try: |
| 82 | + user_obj = await UpdateUser.update( |
| 83 | + obj_id, |
| 84 | + data.dict(exclude_unset=True), |
| 85 | + query_params.headers, |
| 86 | + session=session, |
| 87 | + ) |
| 88 | + except ErrorUpdateUserObject as ex: |
| 89 | + raise BadRequest(ex.description, ex.field) |
| 90 | + except ObjectNotFound as ex: |
| 91 | + raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail=ex.description) |
| 92 | +
|
| 93 | + user = UserSchema.from_orm(user_obj) |
| 94 | + return user |
| 95 | +
|
| 96 | +
|
| 97 | + class UserList: |
| 98 | + @classmethod |
| 99 | + async def get(cls, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> Union[Select, JSONAPIResultListSchema]: |
| 100 | + user_query = select(User) |
| 101 | + dl = SqlalchemyEngine(query=user_query, schema=UserSchema, model=User, session=session) |
| 102 | + count, users_db = await dl.get_collection(qs=query_params) |
| 103 | + total_pages = count // query_params.pagination.size + (count % query_params.pagination.size and 1) |
| 104 | + users: List[UserSchema] = [UserSchema.from_orm(i_user) for i_user in users_db] |
| 105 | + return JSONAPIResultListSchema( |
| 106 | + meta={"count": count, "totalPages": total_pages}, |
| 107 | + data=[{"id": i_obj.id, "attributes": i_obj.dict(), "type": "user"} for i_obj in users], |
| 108 | + ) |
| 109 | +
|
| 110 | + @classmethod |
| 111 | + async def post(cls, data: UserInSchema, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 112 | + try: |
| 113 | + user_obj = await UserFactory.create( |
| 114 | + data=data.dict(), |
| 115 | + mode=FactoryUseMode.production, |
| 116 | + header=query_params.headers, |
| 117 | + session=session, |
| 118 | + ) |
| 119 | + except ErrorCreateUserObject as ex: |
| 120 | + raise BadRequest(ex.description, ex.field) |
| 121 | +
|
| 122 | + user = UserSchema.from_orm(user_obj) |
| 123 | + return user |
| 124 | +
|
0 commit comments