| 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 |
alchemy_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=alchemy_config, app=app) |
| 39 |
document_router = APIRouter() |
| 40 |
# For local development, run an S3-compatible storage service (e.g., RustFS or MinIO) on port 9000 and create the 'static-files' bucket first. |
| 41 |
# Defaults below match pytest-databases >=0.19.0 RustFS fixture credentials; override via env when running real services. |
| 42 |
s3_backend = ObstoreBackend( |
| 43 |
key="local", |
| 44 |
fs="s3://static-files/", |
| 45 |
aws_endpoint="http://localhost:9000", |
| 46 |
aws_access_key_id="pytest-databases-rustfs", |
| 47 |
aws_secret_access_key="pytest-databases-rustfs-secret", # noqa: S106 |
| 48 |
aws_virtual_hosted_style_request=False, |
| 49 |
client_options={"allow_http": True}, |
| 50 |
) |
| 51 |
storages.register_backend(s3_backend) |
| 52 |
|
| 53 |
|
| 54 |
class DocumentModel(base.UUIDBase): |
| 55 |
# we can optionally provide the table name instead of auto-generating it |
| 56 |
__tablename__ = "document" |
| 57 |
name: Mapped[str] |
| 58 |
file: Mapped[FileObject] = mapped_column(StoredObject(backend="local")) |
| 59 |
|
| 60 |
|
| 61 |
class DocumentService(service.SQLAlchemyAsyncRepositoryService[DocumentModel]): |
| 62 |
"""Document repository.""" |
| 63 |
|
| 64 |
class Repo(repository.SQLAlchemyAsyncRepository[DocumentModel]): |
| 65 |
"""Document repository.""" |
| 66 |
|
| 67 |
model_type = DocumentModel |
| 68 |
|
| 69 |
repository_type = Repo |
| 70 |
|
| 71 |
|
| 72 |
# Pydantic Models |
| 73 |
|
| 74 |
|
| 75 |
class Document(BaseModel): |
| 76 |
id: Optional[UUID] |
| 77 |
name: str |
| 78 |
file: Optional[FileObject] = Field(default=None, exclude=True) |
| 79 |
|
| 80 |
@computed_field |
| 81 |
def file_url(self) -> Optional[Union[str, list[str]]]: |
| 82 |
if self.file is None: |
| 83 |
return None |
| 84 |
return self.file.sign() |
| 85 |
|
| 86 |
|
| 87 |
@document_router.get(path="/documents", response_model=service.OffsetPagination[Document]) |
| 88 |
async def list_documents( |
| 89 |
documents_service: Annotated[ |
| 90 |
DocumentService, Depends(alchemy.provide_service(DocumentService, load=[DocumentModel.file])) |
| 91 |
], |
| 92 |
filters: Annotated[ |
| 93 |
list[filters.FilterTypes], |
| 94 |
Depends( |
| 95 |
alchemy.provide_filters( |
| 96 |
{ |
| 97 |
"id_filter": UUID, |
| 98 |
"pagination_type": "limit_offset", |
| 99 |
"search": "name", |
| 100 |
"search_ignore_case": True, |
| 101 |
} |
| 102 |
) |
| 103 |
), |
| 104 |
], |
| 105 |
) -> service.OffsetPagination[Document]: |
| 106 |
results, total = await documents_service.get_many_and_count(*filters) |
| 107 |
return documents_service.to_schema(results, total, filters=filters, schema_type=Document) |
| 108 |
|
| 109 |
|
| 110 |
@document_router.post(path="/documents") |
| 111 |
async def create_document( |
| 112 |
documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 113 |
name: Annotated[str, Form()], |
| 114 |
file: Annotated[Optional[UploadFile], File()] = None, |
| 115 |
) -> Document: |
| 116 |
obj = await documents_service.create( |
| 117 |
DocumentModel( |
| 118 |
name=name, |
| 119 |
file=FileObject( |
| 120 |
backend="local", |
| 121 |
filename=file.filename or "uploaded_file", |
| 122 |
content_type=file.content_type, |
| 123 |
content=await file.read(), |
| 124 |
) |
| 125 |
if file |
| 126 |
else None, |
| 127 |
) |
| 128 |
) |
| 129 |
return documents_service.to_schema(obj, schema_type=Document) |
| 130 |
|
| 131 |
|
| 132 |
@document_router.get(path="/documents/{document_id}") |
| 133 |
async def get_document( |
| 134 |
documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 135 |
document_id: UUID, |
| 136 |
) -> Document: |
| 137 |
obj = await documents_service.get(document_id) |
| 138 |
return documents_service.to_schema(obj, schema_type=Document) |
| 139 |
|
| 140 |
|
| 141 |
@document_router.patch(path="/documents/{document_id}") |
| 142 |
async def update_document( |
| 143 |
documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 144 |
document_id: UUID, |
| 145 |
name: Annotated[Optional[str], Form()] = None, |
| 146 |
file: Annotated[Optional[UploadFile], File()] = None, |
| 147 |
) -> Document: |
| 148 |
update_data: dict[str, Any] = {} |
| 149 |
if name is not None: |
| 150 |
update_data["name"] = name |
| 151 |
if file is not None: |
| 152 |
update_data["file"] = FileObject( |
| 153 |
backend="local", |
| 154 |
filename=file.filename or "uploaded_file", |
| 155 |
content_type=file.content_type, |
| 156 |
content=await file.read(), |
| 157 |
) |
| 158 |
|
| 159 |
obj = await documents_service.update(update_data, item_id=document_id) |
| 160 |
return documents_service.to_schema(obj, schema_type=Document) |
| 161 |
|
| 162 |
|
| 163 |
@document_router.delete(path="/documents/{document_id}") |
| 164 |
async def delete_document( |
| 165 |
documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))], |
| 166 |
document_id: UUID, |
| 167 |
) -> None: |
| 168 |
_ = await documents_service.delete(document_id) |
| 169 |
|
| 170 |
|
| 171 |
app.include_router(document_router) |
| 172 |
|
| 173 |
|
| 174 |
if __name__ == "__main__": |
| 175 |
uvicorn.run(app, host="0.0.0.0", port=8000) # noqa: S104 |