File: fastapi_fileobject.py

package info (click to toggle)
python-advanced-alchemy 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 3,708 kB
  • sloc: python: 25,811; makefile: 162; javascript: 123; sh: 4
file content (171 lines) | stat: -rw-r--r-- 5,310 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# /// script
# dependencies = [
#   "advanced_alchemy[obstore,uuid]",
#   "aiosqlite",
#   "fastapi[standard]",
#   "orjson"
#   "obstore"
# ]
# ///
from typing import Annotated, Any, Optional, Union
from uuid import UUID

import uvicorn
from fastapi import APIRouter, Depends, FastAPI, File, Form, UploadFile
from pydantic import BaseModel, Field, computed_field
from sqlalchemy.orm import Mapped, mapped_column

from advanced_alchemy.extensions.fastapi import (
    AdvancedAlchemy,
    AsyncSessionConfig,
    SQLAlchemyAsyncConfig,
    base,
    filters,
    repository,
    service,
)
from advanced_alchemy.types import FileObject, storages
from advanced_alchemy.types.file_object.backends.obstore import ObstoreBackend
from advanced_alchemy.types.file_object.data_type import StoredObject

sqlalchemy_config = SQLAlchemyAsyncConfig(
    connection_string="sqlite+aiosqlite:///test.sqlite",
    session_config=AsyncSessionConfig(expire_on_commit=False),
    commit_mode="autocommit",
    create_all=True,
)
app = FastAPI()
alchemy = AdvancedAlchemy(config=sqlalchemy_config, app=app)
document_router = APIRouter()
s3_backend = ObstoreBackend(
    key="local",
    fs="s3://static-files/",
    aws_endpoint="http://localhost:9000",
    aws_access_key_id="minioadmin",
    aws_secret_access_key="minioadmin",  # noqa: S106
)
storages.register_backend(s3_backend)


class DocumentModel(base.UUIDBase):
    # we can optionally provide the table name instead of auto-generating it
    __tablename__ = "document"
    name: Mapped[str]
    file: Mapped[FileObject] = mapped_column(StoredObject(backend="local"))


class DocumentService(service.SQLAlchemyAsyncRepositoryService[DocumentModel]):
    """Author repository."""

    class Repo(repository.SQLAlchemyAsyncRepository[DocumentModel]):
        """Author repository."""

        model_type = DocumentModel

    repository_type = Repo


# Pydantic Models


class Document(BaseModel):
    id: Optional[UUID]
    name: str
    file: Optional[FileObject] = Field(default=None, exclude=True)

    @computed_field
    def file_url(self) -> Optional[Union[str, list[str]]]:
        if self.file is None:
            return None
        return self.file.sign()


@document_router.get(path="/documents", response_model=service.OffsetPagination[Document])
async def list_documents(
    documents_service: Annotated[
        DocumentService, Depends(alchemy.provide_service(DocumentService, load=[DocumentModel.file]))
    ],
    filters: Annotated[
        list[filters.FilterTypes],
        Depends(
            alchemy.provide_filters(
                {
                    "id_filter": UUID,
                    "pagination_type": "limit_offset",
                    "search": "name",
                    "search_ignore_case": True,
                }
            )
        ),
    ],
) -> service.OffsetPagination[Document]:
    results, total = await documents_service.list_and_count(*filters)
    return documents_service.to_schema(results, total, filters=filters, schema_type=Document)


@document_router.post(path="/documents")
async def create_document(
    documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))],
    name: Annotated[str, Form()],
    file: Annotated[Optional[UploadFile], File()] = None,
) -> Document:
    obj = await documents_service.create(
        DocumentModel(
            name=name,
            file=FileObject(
                backend="local",
                filename=file.filename or "uploaded_file",
                content_type=file.content_type,
                content=await file.read(),
            )
            if file
            else None,
        )
    )
    return documents_service.to_schema(obj, schema_type=Document)


@document_router.get(path="/documents/{document_id}")
async def get_document(
    documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))],
    document_id: UUID,
) -> Document:
    obj = await documents_service.get(document_id)
    return documents_service.to_schema(obj, schema_type=Document)


@document_router.patch(path="/documents/{document_id}")
async def update_document(
    documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))],
    document_id: UUID,
    name: Annotated[Optional[str], Form()] = None,
    file: Annotated[Optional[UploadFile], File()] = None,
) -> Document:
    update_data: dict[str, Any] = {}
    if name is not None:
        update_data["name"] = name
    if file is not None:
        update_data["file"] = FileObject(
            backend="local",
            filename=file.filename or "uploaded_file",
            content_type=file.content_type,
            content=await file.read(),
        )

    obj = await documents_service.update(update_data, item_id=document_id)
    return documents_service.to_schema(obj, schema_type=Document)


@document_router.delete(path="/documents/{document_id}")
async def delete_document(
    documents_service: Annotated[DocumentService, Depends(alchemy.provide_service(DocumentService))],
    document_id: UUID,
) -> None:
    _ = await documents_service.delete(document_id)


app.include_router(document_router)


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)  # noqa: S104