|
| 1 | +# /// script |
| 2 | +# dependencies = [ |
| 3 | +# "advanced_alchemy[obstore,uuid]", |
| 4 | +# "aiosqlite", |
| 5 | +# "fastapi[standard]", |
| 6 | +# "orjson" |
| 7 | +# "obstore" |
| 8 | +# ] |
| 9 | +# /// |
| 10 | +from typing import Annotated, Any, Optional, Union |
| 11 | +from uuid import UUID |
| 12 | + |
| 13 | +import uvicorn |
| 14 | +from fastapi import APIRouter, Depends, FastAPI, File, Form, UploadFile |
| 15 | +from pydantic import BaseModel, Field, computed_field |
| 16 | +from sqlalchemy.orm import Mapped, mapped_column |
| 17 | + |
| 18 | +from advanced_alchemy.extensions.fastapi import ( |
| 19 | + AdvancedAlchemy, |
| 20 | + AsyncSessionConfig, |
| 21 | + SQLAlchemyAsyncConfig, |
| 22 | + base, |
| 23 | + filters, |
| 24 | + repository, |
| 25 | + service, |
| 26 | +) |
| 27 | +from advanced_alchemy.types import FileObject, storages |
| 28 | +from advanced_alchemy.types.file_object.backends.obstore import ObstoreBackend |
| 29 | +from advanced_alchemy.types.file_object.data_type import StoredObject |
| 30 | + |
| 31 | +sqlalchemy_config = SQLAlchemyAsyncConfig( |
| 32 | + connection_string="sqlite+aiosqlite:///test.sqlite", |
| 33 | + session_config=AsyncSessionConfig(expire_on_commit=False), |
| 34 | + commit_mode="autocommit", |
| 35 | + create_all=True, |
| 36 | +) |
| 37 | +app = FastAPI() |
| 38 | +alchemy = AdvancedAlchemy(config=sqlalchemy_config, app=app) |
| 39 | +document_router = APIRouter() |
| 40 | +s3_backend = ObstoreBackend( |
| 41 | + key="local", |
| 42 | + fs="s3://static-files/", |
| 43 | + aws_endpoint="http://localhost:9000", |
| 44 | + aws_access_key_id="minioadmin", |
| 45 | + aws_secret_access_key="minioadmin", # noqa: S106 |
| 46 | +) |
| 47 | +storages.register_backend(s3_backend) |
| 48 | + |
| 49 | + |
| 50 | +class DocumentModel(base.UUIDBase): |
| 51 | + # we can optionally provide the table name instead of auto-generating it |
| 52 | + __tablename__ = "document" |
| 53 | + name: Mapped[str] |
| 54 | + file: Mapped[FileObject] = mapped_column(StoredObject(backend="local")) |
| 55 | + |
| 56 | + |
| 57 | +class DocumentService(service.SQLAlchemyAsyncRepositoryService[DocumentModel]): |
| 58 | + """Author repository.""" |
| 59 | + |
| 60 | + class Repo(repository.SQLAlchemyAsyncRepository[DocumentModel]): |
| 61 | + """Author repository.""" |
| 62 | + |
| 63 | + model_type = DocumentModel |
| 64 | + |
| 65 | + repository_type = Repo |
| 66 | + |
| 67 | + |
| 68 | +# Pydantic Models |
| 69 | + |
| 70 | + |
| 71 | +class Document(BaseModel): |
| 72 | + id: Optional[UUID] |
| 73 | + name: str |
| 74 | + file: Optional[FileObject] = Field(default=None, exclude=True) |
| 75 | + |
| 76 | + @computed_field |
| 77 | + def file_url(self) -> Optional[Union[str, list[str]]]: |
| 78 | + if self.file is None: |
| 79 | + return None |
| 80 | + return self.file.sign() |
| 81 | + |
| 82 | + |
| 83 | +@document_router.get(path="/documents", response_model=service.OffsetPagination[Document]) |
| 84 | +async def list_documents( |
| 85 | + documents_service: Annotated[ |
| 86 | + DocumentService, Depends(alchemy.provide_service(DocumentService, load=[DocumentModel.file])) |
| 87 | + ], |
| 88 | + filters: Annotated[ |
| 89 | + list[filters.FilterTypes], |
| 90 | + Depends( |
| 91 | + alchemy.provide_filters( |
| 92 | + { |
| 93 | + "id_filter": UUID, |
| 94 | + "pagination_type": "limit_offset", |
| 95 | + "search": "name", |
| 96 | + "search_ignore_case": True, |
| 97 | + } |
| 98 | + ) |
| 99 | + ), |
| 100 | + ], |
| 101 | +) -> service.OffsetPagination[Document]: |
| 102 | + results, total = await documents_service.list_and_count(*filters) |
| 103 | + return documents_service.to_schema(results, total, filters=filters, schema_type=Document) |
| 104 | + |
| 105 | + |
| 106 | +@document_router.post(path="/documents") |
| 107 | +async def create_document( |
| 108 | + documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 109 | + name: Annotated[str, Form()], |
| 110 | + file: Annotated[Optional[UploadFile], File()] = None, |
| 111 | +) -> Document: |
| 112 | + obj = await documents_service.create( |
| 113 | + DocumentModel( |
| 114 | + name=name, |
| 115 | + file=FileObject( |
| 116 | + backend="local", |
| 117 | + filename=file.filename or "uploaded_file", |
| 118 | + content_type=file.content_type, |
| 119 | + content=await file.read(), |
| 120 | + ) |
| 121 | + if file |
| 122 | + else None, |
| 123 | + ) |
| 124 | + ) |
| 125 | + return documents_service.to_schema(obj, schema_type=Document) |
| 126 | + |
| 127 | + |
| 128 | +@document_router.get(path="/documents/{document_id}") |
| 129 | +async def get_document( |
| 130 | + documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 131 | + document_id: UUID, |
| 132 | +) -> Document: |
| 133 | + obj = await documents_service.get(document_id) |
| 134 | + return documents_service.to_schema(obj, schema_type=Document) |
| 135 | + |
| 136 | + |
| 137 | +@document_router.patch(path="/documents/{document_id}") |
| 138 | +async def update_document( |
| 139 | + documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 140 | + document_id: UUID, |
| 141 | + name: Annotated[Optional[str], Form()] = None, |
| 142 | + file: Annotated[Optional[UploadFile], File()] = None, |
| 143 | +) -> Document: |
| 144 | + update_data: dict[str, Any] = {} |
| 145 | + if name is not None: |
| 146 | + update_data["name"] = name |
| 147 | + if file is not None: |
| 148 | + update_data["file"] = FileObject( |
| 149 | + backend="local", |
| 150 | + filename=file.filename or "uploaded_file", |
| 151 | + content_type=file.content_type, |
| 152 | + content=await file.read(), |
| 153 | + ) |
| 154 | + |
| 155 | + obj = await documents_service.update(update_data, item_id=document_id) |
| 156 | + return documents_service.to_schema(obj, schema_type=Document) |
| 157 | + |
| 158 | + |
| 159 | +@document_router.delete(path="/documents/{document_id}") |
| 160 | +async def delete_document( |
| 161 | + documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 162 | + document_id: UUID, |
| 163 | +) -> None: |
| 164 | + _ = await documents_service.delete(document_id) |
| 165 | + |
| 166 | + |
| 167 | +app.include_router(document_router) |
| 168 | + |
| 169 | + |
| 170 | +if __name__ == "__main__": |
| 171 | + uvicorn.run(app, host="0.0.0.0", port=8000) # noqa: S104 |
0 commit comments