fastapi-cls-view 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_cls_view-0.1.0/LICENSE +21 -0
- fastapi_cls_view-0.1.0/PKG-INFO +197 -0
- fastapi_cls_view-0.1.0/README.md +180 -0
- fastapi_cls_view-0.1.0/pyproject.toml +106 -0
- fastapi_cls_view-0.1.0/pyproject.toml.orig +107 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/__init__.py +85 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/__init__.py +0 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/hooks/__init__.py +0 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/hooks/chain.py +102 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/hooks/collect.py +120 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/hooks/decorators.py +158 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/hooks/info.py +84 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/hooks/stream.py +139 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/inherit.py +62 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/member.py +85 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/__init__.py +0 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/binding.py +71 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/context.py +56 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/dependencies.py +71 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/handled.py +27 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/route.py +196 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/routes/route_class.py +67 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/view/__init__.py +0 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/view/config.py +45 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/view/fields.py +185 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/view/generics.py +82 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/_internal/view/markers.py +70 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/decorators.py +150 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/docs.py +150 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/errors.py +150 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/py.typed +0 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/types.py +154 -0
- fastapi_cls_view-0.1.0/src/fastapi_cls_view/views.py +293 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yurii Karabas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-cls-view
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Class-based views for FastAPI: fields as dependencies, routes as methods, hooks as in pydantic
|
|
5
|
+
Author: Yurii Karabas
|
|
6
|
+
Author-email: Yurii Karabas <1998uriyyo@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: fastapi>=0.165.0
|
|
10
|
+
Requires-Dist: fastapi-injected>=0.5.2
|
|
11
|
+
Requires-Dist: sqlalchemy>=2.0.40 ; extra == 'examples'
|
|
12
|
+
Requires-Dist: pyjwt>=2.10.0 ; extra == 'examples'
|
|
13
|
+
Requires-Dist: fastapi-pagination>=0.15.0 ; extra == 'examples'
|
|
14
|
+
Requires-Python: >=3.12
|
|
15
|
+
Provides-Extra: examples
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# fastapi-cls-view
|
|
19
|
+
|
|
20
|
+
Class-based views for FastAPI.
|
|
21
|
+
|
|
22
|
+
A view is a dataclass: its fields are dependencies, its methods are routes, and hooks run around them the way validators run around a pydantic model. Everything goes through FastAPI's own machinery - `Depends`, `APIRouter`, OpenAPI - so nothing you know stops working.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
pip install fastapi-cls-view
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Requires Python 3.12+ and FastAPI 0.165+.
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from typing import Annotated
|
|
36
|
+
|
|
37
|
+
from fastapi import Depends, FastAPI, HTTPException, status
|
|
38
|
+
|
|
39
|
+
from fastapi_cls_view import View, get, post
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Users(View, prefix="/users", tags=["users"]):
|
|
43
|
+
repo: Annotated[UserRepo, Depends(get_repo)]
|
|
44
|
+
limit: int = 10
|
|
45
|
+
|
|
46
|
+
@get("/")
|
|
47
|
+
def index(self) -> list[User]:
|
|
48
|
+
return self.repo.all()[: self.limit]
|
|
49
|
+
|
|
50
|
+
@get("/{user_id}")
|
|
51
|
+
def read(self, user_id: int) -> User:
|
|
52
|
+
if (user := self.repo.get(user_id)) is None:
|
|
53
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
|
54
|
+
|
|
55
|
+
return user
|
|
56
|
+
|
|
57
|
+
@post("/", status_code=status.HTTP_201_CREATED)
|
|
58
|
+
def create(self, user: UserIn) -> User:
|
|
59
|
+
return self.repo.add(user)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
app = FastAPI()
|
|
63
|
+
app.include_router(Users.as_router())
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
- The view is built once per request. Each field is a parameter of it, resolved as FastAPI resolves a route's: `Depends`, a query parameter with a default, `Request`, another view.
|
|
67
|
+
- `get`, `post`, `put`, `patch`, `delete`, `options`, `head`, `trace`, `api_route`, `websocket` and `sse` take what the `APIRouter` methods take.
|
|
68
|
+
- The class keywords are the `APIRouter` options: `prefix`, `tags`, `dependencies`, `responses` and the rest. `view_config = ViewConfig(...)` in the class body does the same.
|
|
69
|
+
- `as_router(include=..., exclude=..., **overrides)` picks routes by name and overrides the config.
|
|
70
|
+
- `Users.read` is the route - `Users.read.url_for(request, user_id=1)` - while `Users(...).read(1)` stays a plain method call.
|
|
71
|
+
|
|
72
|
+
## Hooks
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from fastapi_cls_view import Handler, View, error_hook, get, request_hook, responds
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Items(View, prefix="/items"):
|
|
79
|
+
@request_hook(mode="before")
|
|
80
|
+
def authenticate(self, x_token: Annotated[str | None, Header()] = None) -> None:
|
|
81
|
+
if x_token != "secret":
|
|
82
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED)
|
|
83
|
+
|
|
84
|
+
@request_hook("read") # only for `read`; no names, or "*", is every route
|
|
85
|
+
def shout(self, result: Item) -> Item:
|
|
86
|
+
return result.model_copy(update={"name": result.name.upper()})
|
|
87
|
+
|
|
88
|
+
@request_hook(mode="wrap")
|
|
89
|
+
def traced(self, handler: Handler[Any]) -> Any:
|
|
90
|
+
with span("items"):
|
|
91
|
+
return handler()
|
|
92
|
+
|
|
93
|
+
@responds(status.HTTP_404_NOT_FOUND, description="No such item")
|
|
94
|
+
@error_hook(ItemNotFoundError)
|
|
95
|
+
def not_found(self, exc: Exception) -> Response:
|
|
96
|
+
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_404_NOT_FOUND)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
| Mode | Signature | Runs |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `request` | `(cls, request) -> Response \| None` | Before the view is built, with the plain request. A response answers the request. |
|
|
102
|
+
| `before` | `(self, ...dependencies) -> None` | As a dependency of the route, with parameters of its own. |
|
|
103
|
+
| `after` (default) | `(self, result) -> result` | With what the route returned - or each item of a stream. |
|
|
104
|
+
| `wrap` | `(self, handler) -> result` | Around the route and the hooks defined before it. |
|
|
105
|
+
| `teardown` | `(self, exc: Exception \| None) -> None` | Once the route is done, with its error if it failed. |
|
|
106
|
+
| `background` | `(self) -> None` | Once the response is sent. Not at all if the request failed, even when an error hook answered it. |
|
|
107
|
+
|
|
108
|
+
An `@error_hook(ExcType)` answers an exception with a response; the closest exception type wins. As a method it handles what the route raises, as a `@classmethod` - `(cls, request, exc)` - also what building the view raises. A bare `@error_hook` leaves FastAPI's own `HTTPException` and validation errors alone.
|
|
109
|
+
|
|
110
|
+
`@responds(...)` documents a response of a route, or of every route a hook applies to.
|
|
111
|
+
|
|
112
|
+
## Dependencies
|
|
113
|
+
|
|
114
|
+
A method can be a dependency: resolved once per request, with the view.
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
class Users(View, prefix="/users"):
|
|
118
|
+
@dependency
|
|
119
|
+
def user(self, user_id: int) -> User:
|
|
120
|
+
return find_user(user_id)
|
|
121
|
+
|
|
122
|
+
@get("/{user_id}")
|
|
123
|
+
def read(self, user: Annotated[User, Depends(user)]) -> User:
|
|
124
|
+
return user
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Posts(View, prefix="/users/{user_id}/posts"):
|
|
128
|
+
route: CurrentRoute # the route being served
|
|
129
|
+
|
|
130
|
+
@get("/")
|
|
131
|
+
def index(self, user: Annotated[User, Depends(Users.user)]) -> list[Post]:
|
|
132
|
+
return posts_of(user)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Outside a view, depend on `Users.user.dependency`.
|
|
136
|
+
|
|
137
|
+
## Lifespan
|
|
138
|
+
|
|
139
|
+
A `@lifespan` hook runs with the app: startup before the `yield`, shutdown after it. The bases' hooks start first and shut down last.
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
class Users(View, prefix="/users"):
|
|
143
|
+
pool: ClassVar[Pool]
|
|
144
|
+
|
|
145
|
+
@lifespan
|
|
146
|
+
@classmethod
|
|
147
|
+
async def open_pool(cls, app: FastAPI) -> AsyncIterator[None]:
|
|
148
|
+
async with create_pool() as cls.pool:
|
|
149
|
+
yield
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Inheritance and generics
|
|
153
|
+
|
|
154
|
+
Routes, hooks, dependencies and config are inherited as Python resolves attributes. Override a route with a plain method, drop it with `None`.
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
class CRUD[M: BaseModel](View):
|
|
158
|
+
@get("/{item_id}")
|
|
159
|
+
def read(self, item_id: int) -> M: ...
|
|
160
|
+
|
|
161
|
+
@put("/{item_id}")
|
|
162
|
+
def save(self, item_id: int, item: M) -> M: ...
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Tags(CRUD[Tag], prefix="/tags"):
|
|
166
|
+
save = None # read-only
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
app.include_router(Tags.as_router())
|
|
170
|
+
app.include_router(CRUD[User].as_router(prefix="/users"))
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Testing
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
with Users.override(app, repo=FakeRepo()):
|
|
177
|
+
assert client.get("/users/").json() == [...]
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## Examples
|
|
181
|
+
|
|
182
|
+
Working apps for each of the above are in [`examples/`](examples), on SQLAlchemy with an in-memory SQLite database:
|
|
183
|
+
|
|
184
|
+
| Example | Shows | With |
|
|
185
|
+
|---|---|---|
|
|
186
|
+
| [`basic`](examples/basic.py) | A CRUD view with a session field | SQLAlchemy |
|
|
187
|
+
| [`hooks`](examples/hooks.py) | A transaction per request, an API key, timing, an audit log, 404 and 409 answers | SQLAlchemy |
|
|
188
|
+
| [`dependencies`](examples/dependencies.py) | A bearer-token `current_user` shared by two views | PyJWT |
|
|
189
|
+
| [`lifespan`](examples/lifespan.py) | A view that owns its engine | SQLAlchemy |
|
|
190
|
+
| [`generics`](examples/generics.py) | A generic paginated `CRUD[Out, In]` view | fastapi-pagination |
|
|
191
|
+
| [`streaming`](examples/streaming.py) | Rows as JSON lines and server-sent events, a websocket chat room | SQLAlchemy |
|
|
192
|
+
| [`overrides`](examples/overrides.py) | A test that serves a view with its own database | SQLAlchemy |
|
|
193
|
+
|
|
194
|
+
```sh
|
|
195
|
+
pip install "fastapi-cls-view[examples]"
|
|
196
|
+
fastapi dev examples/basic.py
|
|
197
|
+
```
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# fastapi-cls-view
|
|
2
|
+
|
|
3
|
+
Class-based views for FastAPI.
|
|
4
|
+
|
|
5
|
+
A view is a dataclass: its fields are dependencies, its methods are routes, and hooks run around them the way validators run around a pydantic model. Everything goes through FastAPI's own machinery - `Depends`, `APIRouter`, OpenAPI - so nothing you know stops working.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install fastapi-cls-view
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires Python 3.12+ and FastAPI 0.165+.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from typing import Annotated
|
|
19
|
+
|
|
20
|
+
from fastapi import Depends, FastAPI, HTTPException, status
|
|
21
|
+
|
|
22
|
+
from fastapi_cls_view import View, get, post
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Users(View, prefix="/users", tags=["users"]):
|
|
26
|
+
repo: Annotated[UserRepo, Depends(get_repo)]
|
|
27
|
+
limit: int = 10
|
|
28
|
+
|
|
29
|
+
@get("/")
|
|
30
|
+
def index(self) -> list[User]:
|
|
31
|
+
return self.repo.all()[: self.limit]
|
|
32
|
+
|
|
33
|
+
@get("/{user_id}")
|
|
34
|
+
def read(self, user_id: int) -> User:
|
|
35
|
+
if (user := self.repo.get(user_id)) is None:
|
|
36
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND)
|
|
37
|
+
|
|
38
|
+
return user
|
|
39
|
+
|
|
40
|
+
@post("/", status_code=status.HTTP_201_CREATED)
|
|
41
|
+
def create(self, user: UserIn) -> User:
|
|
42
|
+
return self.repo.add(user)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
app = FastAPI()
|
|
46
|
+
app.include_router(Users.as_router())
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- The view is built once per request. Each field is a parameter of it, resolved as FastAPI resolves a route's: `Depends`, a query parameter with a default, `Request`, another view.
|
|
50
|
+
- `get`, `post`, `put`, `patch`, `delete`, `options`, `head`, `trace`, `api_route`, `websocket` and `sse` take what the `APIRouter` methods take.
|
|
51
|
+
- The class keywords are the `APIRouter` options: `prefix`, `tags`, `dependencies`, `responses` and the rest. `view_config = ViewConfig(...)` in the class body does the same.
|
|
52
|
+
- `as_router(include=..., exclude=..., **overrides)` picks routes by name and overrides the config.
|
|
53
|
+
- `Users.read` is the route - `Users.read.url_for(request, user_id=1)` - while `Users(...).read(1)` stays a plain method call.
|
|
54
|
+
|
|
55
|
+
## Hooks
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from fastapi_cls_view import Handler, View, error_hook, get, request_hook, responds
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Items(View, prefix="/items"):
|
|
62
|
+
@request_hook(mode="before")
|
|
63
|
+
def authenticate(self, x_token: Annotated[str | None, Header()] = None) -> None:
|
|
64
|
+
if x_token != "secret":
|
|
65
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED)
|
|
66
|
+
|
|
67
|
+
@request_hook("read") # only for `read`; no names, or "*", is every route
|
|
68
|
+
def shout(self, result: Item) -> Item:
|
|
69
|
+
return result.model_copy(update={"name": result.name.upper()})
|
|
70
|
+
|
|
71
|
+
@request_hook(mode="wrap")
|
|
72
|
+
def traced(self, handler: Handler[Any]) -> Any:
|
|
73
|
+
with span("items"):
|
|
74
|
+
return handler()
|
|
75
|
+
|
|
76
|
+
@responds(status.HTTP_404_NOT_FOUND, description="No such item")
|
|
77
|
+
@error_hook(ItemNotFoundError)
|
|
78
|
+
def not_found(self, exc: Exception) -> Response:
|
|
79
|
+
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_404_NOT_FOUND)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
| Mode | Signature | Runs |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| `request` | `(cls, request) -> Response \| None` | Before the view is built, with the plain request. A response answers the request. |
|
|
85
|
+
| `before` | `(self, ...dependencies) -> None` | As a dependency of the route, with parameters of its own. |
|
|
86
|
+
| `after` (default) | `(self, result) -> result` | With what the route returned - or each item of a stream. |
|
|
87
|
+
| `wrap` | `(self, handler) -> result` | Around the route and the hooks defined before it. |
|
|
88
|
+
| `teardown` | `(self, exc: Exception \| None) -> None` | Once the route is done, with its error if it failed. |
|
|
89
|
+
| `background` | `(self) -> None` | Once the response is sent. Not at all if the request failed, even when an error hook answered it. |
|
|
90
|
+
|
|
91
|
+
An `@error_hook(ExcType)` answers an exception with a response; the closest exception type wins. As a method it handles what the route raises, as a `@classmethod` - `(cls, request, exc)` - also what building the view raises. A bare `@error_hook` leaves FastAPI's own `HTTPException` and validation errors alone.
|
|
92
|
+
|
|
93
|
+
`@responds(...)` documents a response of a route, or of every route a hook applies to.
|
|
94
|
+
|
|
95
|
+
## Dependencies
|
|
96
|
+
|
|
97
|
+
A method can be a dependency: resolved once per request, with the view.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
class Users(View, prefix="/users"):
|
|
101
|
+
@dependency
|
|
102
|
+
def user(self, user_id: int) -> User:
|
|
103
|
+
return find_user(user_id)
|
|
104
|
+
|
|
105
|
+
@get("/{user_id}")
|
|
106
|
+
def read(self, user: Annotated[User, Depends(user)]) -> User:
|
|
107
|
+
return user
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Posts(View, prefix="/users/{user_id}/posts"):
|
|
111
|
+
route: CurrentRoute # the route being served
|
|
112
|
+
|
|
113
|
+
@get("/")
|
|
114
|
+
def index(self, user: Annotated[User, Depends(Users.user)]) -> list[Post]:
|
|
115
|
+
return posts_of(user)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Outside a view, depend on `Users.user.dependency`.
|
|
119
|
+
|
|
120
|
+
## Lifespan
|
|
121
|
+
|
|
122
|
+
A `@lifespan` hook runs with the app: startup before the `yield`, shutdown after it. The bases' hooks start first and shut down last.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
class Users(View, prefix="/users"):
|
|
126
|
+
pool: ClassVar[Pool]
|
|
127
|
+
|
|
128
|
+
@lifespan
|
|
129
|
+
@classmethod
|
|
130
|
+
async def open_pool(cls, app: FastAPI) -> AsyncIterator[None]:
|
|
131
|
+
async with create_pool() as cls.pool:
|
|
132
|
+
yield
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Inheritance and generics
|
|
136
|
+
|
|
137
|
+
Routes, hooks, dependencies and config are inherited as Python resolves attributes. Override a route with a plain method, drop it with `None`.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
class CRUD[M: BaseModel](View):
|
|
141
|
+
@get("/{item_id}")
|
|
142
|
+
def read(self, item_id: int) -> M: ...
|
|
143
|
+
|
|
144
|
+
@put("/{item_id}")
|
|
145
|
+
def save(self, item_id: int, item: M) -> M: ...
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class Tags(CRUD[Tag], prefix="/tags"):
|
|
149
|
+
save = None # read-only
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
app.include_router(Tags.as_router())
|
|
153
|
+
app.include_router(CRUD[User].as_router(prefix="/users"))
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## Testing
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
with Users.override(app, repo=FakeRepo()):
|
|
160
|
+
assert client.get("/users/").json() == [...]
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Examples
|
|
164
|
+
|
|
165
|
+
Working apps for each of the above are in [`examples/`](examples), on SQLAlchemy with an in-memory SQLite database:
|
|
166
|
+
|
|
167
|
+
| Example | Shows | With |
|
|
168
|
+
|---|---|---|
|
|
169
|
+
| [`basic`](examples/basic.py) | A CRUD view with a session field | SQLAlchemy |
|
|
170
|
+
| [`hooks`](examples/hooks.py) | A transaction per request, an API key, timing, an audit log, 404 and 409 answers | SQLAlchemy |
|
|
171
|
+
| [`dependencies`](examples/dependencies.py) | A bearer-token `current_user` shared by two views | PyJWT |
|
|
172
|
+
| [`lifespan`](examples/lifespan.py) | A view that owns its engine | SQLAlchemy |
|
|
173
|
+
| [`generics`](examples/generics.py) | A generic paginated `CRUD[Out, In]` view | fastapi-pagination |
|
|
174
|
+
| [`streaming`](examples/streaming.py) | Rows as JSON lines and server-sent events, a websocket chat room | SQLAlchemy |
|
|
175
|
+
| [`overrides`](examples/overrides.py) | A test that serves a view with its own database | SQLAlchemy |
|
|
176
|
+
|
|
177
|
+
```sh
|
|
178
|
+
pip install "fastapi-cls-view[examples]"
|
|
179
|
+
fastapi dev examples/basic.py
|
|
180
|
+
```
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fastapi-cls-view"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Class-based views for FastAPI: fields as dependencies, routes as methods, hooks as in pydantic"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.12"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"fastapi>=0.165.0",
|
|
11
|
+
"fastapi-injected>=0.5.2",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[[project.authors]]
|
|
15
|
+
name = "Yurii Karabas"
|
|
16
|
+
email = "1998uriyyo@gmail.com"
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
examples = [
|
|
20
|
+
"sqlalchemy>=2.0.40",
|
|
21
|
+
"pyjwt>=2.10.0",
|
|
22
|
+
"fastapi-pagination>=0.15.0",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
27
|
+
build-backend = "uv_build"
|
|
28
|
+
|
|
29
|
+
[dependency-groups]
|
|
30
|
+
dev = [
|
|
31
|
+
"httpx2>=2.16.2",
|
|
32
|
+
"pytest>=9.2.0",
|
|
33
|
+
"pytest-cov>=7.1.0",
|
|
34
|
+
"ruff>=0.17.6",
|
|
35
|
+
"ty>=0.0.107",
|
|
36
|
+
"pre-commit>=4.6.1",
|
|
37
|
+
"fastapi-cls-view[examples]",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[tool.ruff]
|
|
41
|
+
line-length = 120
|
|
42
|
+
target-version = "py312"
|
|
43
|
+
|
|
44
|
+
[tool.ruff.lint]
|
|
45
|
+
select = ["ALL"]
|
|
46
|
+
ignore = [
|
|
47
|
+
"S101",
|
|
48
|
+
"PLR2004",
|
|
49
|
+
"TRY003",
|
|
50
|
+
"D",
|
|
51
|
+
"FA",
|
|
52
|
+
"ANN",
|
|
53
|
+
"FIX",
|
|
54
|
+
"TD",
|
|
55
|
+
"ARG",
|
|
56
|
+
"FBT",
|
|
57
|
+
"EM",
|
|
58
|
+
"TC",
|
|
59
|
+
"CPY",
|
|
60
|
+
]
|
|
61
|
+
exclude = [
|
|
62
|
+
".bzr",
|
|
63
|
+
".direnv",
|
|
64
|
+
".eggs",
|
|
65
|
+
".git",
|
|
66
|
+
".hg",
|
|
67
|
+
".mypy_cache",
|
|
68
|
+
".nox",
|
|
69
|
+
".pants.d",
|
|
70
|
+
".ruff_cache",
|
|
71
|
+
".svn",
|
|
72
|
+
".tox",
|
|
73
|
+
".venv",
|
|
74
|
+
"__pypackages__",
|
|
75
|
+
"_build",
|
|
76
|
+
"buck-out",
|
|
77
|
+
"build",
|
|
78
|
+
"dist",
|
|
79
|
+
"node_modules",
|
|
80
|
+
"venv",
|
|
81
|
+
".venv",
|
|
82
|
+
]
|
|
83
|
+
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
|
84
|
+
|
|
85
|
+
[tool.ruff.lint.per-file-ignores]
|
|
86
|
+
|
|
87
|
+
[tool.ruff.lint.mccabe]
|
|
88
|
+
max-complexity = 10
|
|
89
|
+
|
|
90
|
+
[tool.pytest.ini_options]
|
|
91
|
+
pythonpath = ["."]
|
|
92
|
+
testpaths = ["tests"]
|
|
93
|
+
|
|
94
|
+
[tool.coverage.paths]
|
|
95
|
+
source = ["fastapi_cls_view"]
|
|
96
|
+
|
|
97
|
+
[tool.coverage.run]
|
|
98
|
+
source = ["fastapi_cls_view"]
|
|
99
|
+
|
|
100
|
+
[tool.coverage.report]
|
|
101
|
+
exclude_lines = [
|
|
102
|
+
"pragma: no cover",
|
|
103
|
+
"@abstractmethod",
|
|
104
|
+
"@overload",
|
|
105
|
+
"if TYPE_CHECKING:",
|
|
106
|
+
]
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fastapi-cls-view"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Class-based views for FastAPI: fields as dependencies, routes as methods, hooks as in pydantic"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Yurii Karabas", email = "1998uriyyo@gmail.com" }]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"fastapi>=0.165.0",
|
|
12
|
+
"fastapi-injected>=0.5.2",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
examples = [
|
|
17
|
+
"sqlalchemy>=2.0.40",
|
|
18
|
+
"pyjwt>=2.10.0",
|
|
19
|
+
"fastapi-pagination>=0.15.0",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
24
|
+
build-backend = "uv_build"
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
dev = [
|
|
28
|
+
"httpx2>=2.16.2",
|
|
29
|
+
"pytest>=9.2.0",
|
|
30
|
+
"pytest-cov>=7.1.0",
|
|
31
|
+
"ruff>=0.17.6",
|
|
32
|
+
"ty>=0.0.107",
|
|
33
|
+
"pre-commit>=4.6.1",
|
|
34
|
+
"fastapi-cls-view[examples]",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[tool.ruff]
|
|
38
|
+
line-length = 120
|
|
39
|
+
target-version = "py312"
|
|
40
|
+
|
|
41
|
+
[tool.ruff.lint]
|
|
42
|
+
select = [
|
|
43
|
+
"ALL", # select all checks by default
|
|
44
|
+
]
|
|
45
|
+
ignore = [
|
|
46
|
+
# single rule exclude
|
|
47
|
+
"S101", # allow assert usage
|
|
48
|
+
"PLR2004", # allow to compare with "magic numbers"
|
|
49
|
+
"TRY003", # allow message in exception class
|
|
50
|
+
|
|
51
|
+
# full rule exclude
|
|
52
|
+
"D", # ignore docstrings
|
|
53
|
+
"FA", # ignore future annotations
|
|
54
|
+
"ANN", # ignore annotations
|
|
55
|
+
"FIX", # ignore FIXMEs
|
|
56
|
+
"TD", # ignore all TODOs
|
|
57
|
+
"ARG", # ignore unused arguments
|
|
58
|
+
"FBT", # ignore flake8-boolean-trap
|
|
59
|
+
"EM", # ignore error message formatting
|
|
60
|
+
"TC", # ignore type checking
|
|
61
|
+
"CPY", # ignore copyright
|
|
62
|
+
]
|
|
63
|
+
exclude = [
|
|
64
|
+
".bzr",
|
|
65
|
+
".direnv",
|
|
66
|
+
".eggs",
|
|
67
|
+
".git",
|
|
68
|
+
".hg",
|
|
69
|
+
".mypy_cache",
|
|
70
|
+
".nox",
|
|
71
|
+
".pants.d",
|
|
72
|
+
".ruff_cache",
|
|
73
|
+
".svn",
|
|
74
|
+
".tox",
|
|
75
|
+
".venv",
|
|
76
|
+
"__pypackages__",
|
|
77
|
+
"_build",
|
|
78
|
+
"buck-out",
|
|
79
|
+
"build",
|
|
80
|
+
"dist",
|
|
81
|
+
"node_modules",
|
|
82
|
+
"venv",
|
|
83
|
+
".venv",
|
|
84
|
+
]
|
|
85
|
+
per-file-ignores = { }
|
|
86
|
+
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
|
87
|
+
|
|
88
|
+
[tool.ruff.lint.mccabe]
|
|
89
|
+
max-complexity = 10
|
|
90
|
+
|
|
91
|
+
[tool.pytest.ini_options]
|
|
92
|
+
pythonpath = ["."]
|
|
93
|
+
testpaths = ["tests"]
|
|
94
|
+
|
|
95
|
+
[tool.coverage.paths]
|
|
96
|
+
source = ["fastapi_cls_view"]
|
|
97
|
+
|
|
98
|
+
[tool.coverage.run]
|
|
99
|
+
source = ["fastapi_cls_view"]
|
|
100
|
+
|
|
101
|
+
[tool.coverage.report]
|
|
102
|
+
exclude_lines = [
|
|
103
|
+
"pragma: no cover",
|
|
104
|
+
"@abstractmethod",
|
|
105
|
+
"@overload",
|
|
106
|
+
"if TYPE_CHECKING:",
|
|
107
|
+
]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
from fastapi_cls_view._internal.hooks.decorators import error_hook, lifespan, request_hook
|
|
2
|
+
from fastapi_cls_view._internal.hooks.info import ViewHook
|
|
3
|
+
from fastapi_cls_view._internal.routes.context import CurrentRoute, RouteContext, current_route
|
|
4
|
+
from fastapi_cls_view._internal.routes.dependencies import ViewDependency, dependency
|
|
5
|
+
from fastapi_cls_view._internal.routes.route import ViewRoute
|
|
6
|
+
from fastapi_cls_view._internal.view.fields import ViewField
|
|
7
|
+
|
|
8
|
+
from .decorators import api_route, delete, get, head, options, patch, post, put, sse, trace, websocket
|
|
9
|
+
from .docs import Example, ResponseDoc, ResponseHeader, responds
|
|
10
|
+
from .errors import (
|
|
11
|
+
DecoratorUsageError,
|
|
12
|
+
MissingSelfError,
|
|
13
|
+
NotAViewRouteError,
|
|
14
|
+
OverrideError,
|
|
15
|
+
ReservedNameError,
|
|
16
|
+
StreamHookError,
|
|
17
|
+
UnboundRouteError,
|
|
18
|
+
UnknownClassKeywordsError,
|
|
19
|
+
UnknownDependencyError,
|
|
20
|
+
UnknownFieldError,
|
|
21
|
+
UnknownHookRouteError,
|
|
22
|
+
UnknownRouteError,
|
|
23
|
+
UnknownViewConfigError,
|
|
24
|
+
UnsupportedHookError,
|
|
25
|
+
UnsupportedViewOptionError,
|
|
26
|
+
ViewDependencyCycleError,
|
|
27
|
+
ViewError,
|
|
28
|
+
ViewNotReadyError,
|
|
29
|
+
)
|
|
30
|
+
from .types import APIRouteOptions, Handler, HookMode, RouteOptions, ViewConfig, WebSocketOptions
|
|
31
|
+
from .views import View
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"APIRouteOptions",
|
|
35
|
+
"CurrentRoute",
|
|
36
|
+
"DecoratorUsageError",
|
|
37
|
+
"Example",
|
|
38
|
+
"Handler",
|
|
39
|
+
"HookMode",
|
|
40
|
+
"MissingSelfError",
|
|
41
|
+
"NotAViewRouteError",
|
|
42
|
+
"OverrideError",
|
|
43
|
+
"ReservedNameError",
|
|
44
|
+
"ResponseDoc",
|
|
45
|
+
"ResponseHeader",
|
|
46
|
+
"RouteContext",
|
|
47
|
+
"RouteOptions",
|
|
48
|
+
"StreamHookError",
|
|
49
|
+
"UnboundRouteError",
|
|
50
|
+
"UnknownClassKeywordsError",
|
|
51
|
+
"UnknownDependencyError",
|
|
52
|
+
"UnknownFieldError",
|
|
53
|
+
"UnknownHookRouteError",
|
|
54
|
+
"UnknownRouteError",
|
|
55
|
+
"UnknownViewConfigError",
|
|
56
|
+
"UnsupportedHookError",
|
|
57
|
+
"UnsupportedViewOptionError",
|
|
58
|
+
"View",
|
|
59
|
+
"ViewConfig",
|
|
60
|
+
"ViewDependency",
|
|
61
|
+
"ViewDependencyCycleError",
|
|
62
|
+
"ViewError",
|
|
63
|
+
"ViewField",
|
|
64
|
+
"ViewHook",
|
|
65
|
+
"ViewNotReadyError",
|
|
66
|
+
"ViewRoute",
|
|
67
|
+
"WebSocketOptions",
|
|
68
|
+
"api_route",
|
|
69
|
+
"current_route",
|
|
70
|
+
"delete",
|
|
71
|
+
"dependency",
|
|
72
|
+
"error_hook",
|
|
73
|
+
"get",
|
|
74
|
+
"head",
|
|
75
|
+
"lifespan",
|
|
76
|
+
"options",
|
|
77
|
+
"patch",
|
|
78
|
+
"post",
|
|
79
|
+
"put",
|
|
80
|
+
"request_hook",
|
|
81
|
+
"responds",
|
|
82
|
+
"sse",
|
|
83
|
+
"trace",
|
|
84
|
+
"websocket",
|
|
85
|
+
]
|
|
File without changes
|
|
File without changes
|