fapilot 0.1.0__py3-none-any.whl

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.
fapilot/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from fapilot.core.application import Fapilot, create_app
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = ["Fapilot", "__version__", "create_app"]
@@ -0,0 +1,5 @@
1
+ from fapilot.apps.config import AppConfig
2
+ from fapilot.apps.registry import AppRegistry
3
+
4
+ __all__ = ["AppConfig", "AppRegistry"]
5
+
fapilot/apps/config.py ADDED
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ from fastapi import APIRouter
7
+
8
+
9
+ @dataclass(slots=True)
10
+ class AppConfig:
11
+ name: str
12
+ label: str | None = None
13
+ verbose_name: str | None = None
14
+ router: APIRouter | None = None
15
+ router_prefix: str | None = None
16
+ tortoise_models: list[str] = field(default_factory=list)
17
+ migrations_package: str | None = None
18
+
19
+ def ready(self) -> None:
20
+ """Hook called after every app is imported and registered."""
21
+
22
+ @property
23
+ def app_label(self) -> str:
24
+ return self.label or self.name.rsplit(".", 1)[-1]
25
+
26
+ def as_tortoise_app(self) -> dict[str, Any]:
27
+ models = [*self.tortoise_models]
28
+ if self.migrations_package is not None:
29
+ models.append(self.migrations_package)
30
+ return {"models": models, "default_connection": "default"}
31
+
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+ from importlib import import_module
5
+
6
+ from fapilot.apps.config import AppConfig
7
+
8
+
9
+ class AppRegistry:
10
+ def __init__(self) -> None:
11
+ self._apps: dict[str, AppConfig] = {}
12
+ self.ready = False
13
+
14
+ def populate(self, installed_apps: Iterable[str]) -> None:
15
+ if self.ready:
16
+ return
17
+ for dotted_path in installed_apps:
18
+ app_config = self._load_config(dotted_path)
19
+ label = app_config.app_label
20
+ if label in self._apps:
21
+ raise RuntimeError(f"Duplicate app label: {label}")
22
+ self._apps[label] = app_config
23
+ for app_config in self._apps.values():
24
+ app_config.ready()
25
+ self.ready = True
26
+
27
+ def get_app(self, label: str) -> AppConfig:
28
+ return self._apps[label]
29
+
30
+ def get_apps(self) -> list[AppConfig]:
31
+ return list(self._apps.values())
32
+
33
+ def _load_config(self, dotted_path: str) -> AppConfig:
34
+ module_path, _, class_name = dotted_path.rpartition(".")
35
+ if not module_path:
36
+ module_path = f"{dotted_path}.apps"
37
+ class_name = "Config"
38
+ module = import_module(module_path)
39
+ config_cls = getattr(module, class_name)
40
+ config = config_cls()
41
+ if not isinstance(config, AppConfig):
42
+ raise TypeError(f"{dotted_path} must instantiate fapilot.apps.AppConfig")
43
+ return config
@@ -0,0 +1,5 @@
1
+ from fapilot.auth.jwt import create_access_token, decode_access_token
2
+ from fapilot.auth.passwords import hash_password, verify_password
3
+
4
+ __all__ = ["create_access_token", "decode_access_token", "hash_password", "verify_password"]
5
+
fapilot/auth/jwt.py ADDED
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import UTC, datetime, timedelta
4
+ from typing import Any
5
+
6
+ from jose import JWTError, jwt
7
+
8
+ from fapilot.conf import get_settings
9
+
10
+
11
+ def create_access_token(subject: str, claims: dict[str, Any] | None = None) -> str:
12
+ settings = get_settings()
13
+ jwt_settings = settings.JWT_SETTINGS
14
+ expires_at = datetime.now(UTC) + timedelta(minutes=jwt_settings.access_token_expire_minutes)
15
+ payload = {
16
+ "sub": subject,
17
+ "iss": jwt_settings.issuer,
18
+ "exp": expires_at,
19
+ **(claims or {}),
20
+ }
21
+ return jwt.encode(payload, settings.SECRET_KEY, algorithm=jwt_settings.algorithm)
22
+
23
+
24
+ def decode_access_token(token: str) -> dict[str, Any] | None:
25
+ settings = get_settings()
26
+ try:
27
+ return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_SETTINGS.algorithm])
28
+ except JWTError:
29
+ return None
30
+
@@ -0,0 +1,14 @@
1
+ from __future__ import annotations
2
+
3
+ from passlib.context import CryptContext
4
+
5
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
6
+
7
+
8
+ def hash_password(password: str) -> str:
9
+ return pwd_context.hash(password)
10
+
11
+
12
+ def verify_password(password: str, hashed_password: str) -> bool:
13
+ return pwd_context.verify(password, hashed_password)
14
+
@@ -0,0 +1,4 @@
1
+ from fapilot.background.tasks import TaskQueue
2
+
3
+ __all__ = ["TaskQueue"]
4
+
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Callable, Coroutine
5
+ from typing import Any
6
+
7
+
8
+ class TaskQueue:
9
+ def spawn(
10
+ self,
11
+ func: Callable[..., Coroutine[Any, Any, Any]],
12
+ *args: Any,
13
+ **kwargs: Any,
14
+ ) -> asyncio.Task:
15
+ return asyncio.create_task(func(*args, **kwargs))
fapilot/cli.py ADDED
@@ -0,0 +1,218 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ from fapilot.db.migrations import AerichMigrationBackend
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser(prog="fapilot")
12
+ subparsers = parser.add_subparsers(dest="command", required=True)
13
+ startproject = subparsers.add_parser("startproject")
14
+ startproject.add_argument("name")
15
+ startapp = subparsers.add_parser("startapp")
16
+ startapp.add_argument("name")
17
+ makemigrations = subparsers.add_parser("makemigrations")
18
+ makemigrations.add_argument("--name")
19
+ subparsers.add_parser("migrate")
20
+ runserver = subparsers.add_parser("runserver")
21
+ runserver.add_argument("--host", default="127.0.0.1")
22
+ runserver.add_argument("--port", default="8000")
23
+ args = parser.parse_args()
24
+
25
+ if args.command == "startproject":
26
+ start_project(args.name)
27
+ elif args.command == "startapp":
28
+ start_app(args.name)
29
+ elif args.command == "makemigrations":
30
+ AerichMigrationBackend().makemigrations(args.name)
31
+ elif args.command == "migrate":
32
+ AerichMigrationBackend().migrate()
33
+ elif args.command == "runserver":
34
+ subprocess.run(
35
+ ["uvicorn", "config.asgi:app", "--host", args.host, "--port", args.port, "--reload"],
36
+ check=True,
37
+ )
38
+
39
+
40
+ def start_project(name: str) -> None:
41
+ root = Path(name)
42
+ root.mkdir()
43
+ for directory in ["config", "apps", "common", "tests"]:
44
+ (root / directory).mkdir()
45
+ (root / directory / "__init__.py").write_text("", encoding="utf-8")
46
+ _write(root / "manage.py", MANAGE)
47
+ _write(root / "config/settings.py", SETTINGS)
48
+ _write(root / "config/database.py", DATABASE)
49
+ _write(root / "config/urls.py", URLS)
50
+ _write(root / "config/asgi.py", ASGI)
51
+ _write(root / "config/logging.py", "LOGGING = {}\n")
52
+ _write(root / "common/crud.py", "from fapilot.crud import CRUDRouterService\n")
53
+ _write(root / "common/pagination.py", "from fapilot.pagination import Page, Pagination\n")
54
+ _write(root / "common/filtering.py", "from fapilot.filtering import pick_filters\n")
55
+ _write(root / "common/exceptions.py", "from fapilot.exceptions import FapilotError\n")
56
+ _write(
57
+ root / "common/permissions.py",
58
+ "from fapilot.permissions import AllowAny, IsAuthenticated\n",
59
+ )
60
+ _write(root / "common/middleware.py", "from fapilot.middleware import install_cors\n")
61
+ _write(root / "common/responses.py", "from fapilot.responses import ok\n")
62
+ _write(root / "common/events.py", "from fapilot.events import SignalDispatcher\n")
63
+ _write(root / "common/models.py", "from tortoise import fields, models\n")
64
+ _write(root / "common/schemas.py", "from pydantic import BaseModel, ConfigDict\n")
65
+ _write(root / "common/utils.py", "\n")
66
+ _write(root / ".env", ENV)
67
+ _write(root / ".env.example", ENV)
68
+ _write(root / ".gitignore", GITIGNORE)
69
+ _write(root / "README.md", PROJECT_README.format(name=name))
70
+ _write(root / "Dockerfile", DOCKERFILE)
71
+ _write(root / "docker-compose.yml", COMPOSE)
72
+ _write(root / "pyproject.toml", PROJECT_PYPROJECT.format(name=name))
73
+
74
+
75
+ def start_app(name: str) -> None:
76
+ app_dir = Path("apps") / name
77
+ app_dir.mkdir(parents=True)
78
+ (app_dir / "tests").mkdir()
79
+ (app_dir / "migrations").mkdir()
80
+ for file_name, content in APP_FILES.items():
81
+ class_name = name.title().replace("_", "")
82
+ _write(app_dir / file_name, content.format(name=name, class_name=class_name))
83
+ _write(app_dir / "tests/__init__.py", "")
84
+ _write(app_dir / "migrations/__init__.py", "")
85
+
86
+
87
+ def _write(path: Path, content: str) -> None:
88
+ path.write_text(content, encoding="utf-8")
89
+
90
+
91
+ MANAGE = """#!/usr/bin/env python
92
+ from fapilot.cli import main
93
+
94
+ if __name__ == "__main__":
95
+ main()
96
+ """
97
+
98
+ SETTINGS = '''from fapilot.conf import FapilotSettings
99
+
100
+ DEBUG = True
101
+ SECRET_KEY = "change-me"
102
+ ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
103
+ DATABASE_URL = "sqlite://db.sqlite3"
104
+ INSTALLED_APPS = []
105
+ MIDDLEWARE = ["common.middleware.install_cors"]
106
+ CORS_ALLOWED_ORIGINS = []
107
+ TIME_ZONE = "UTC"
108
+ LANGUAGE_CODE = "en-us"
109
+ API_PREFIX = "/api"
110
+ DEFAULT_PAGE_SIZE = 20
111
+ MAX_PAGE_SIZE = 100
112
+ AUTH_USER_MODEL = "users.User"
113
+ JWT_SETTINGS = FapilotSettings().JWT_SETTINGS
114
+ LOGGING = {}
115
+ '''
116
+
117
+ DATABASE = """import os
118
+
119
+ from fapilot.apps import AppRegistry
120
+ from fapilot.conf import load_settings
121
+ from fapilot.db.tortoise import build_tortoise_config
122
+
123
+ settings = load_settings("config.settings")
124
+ registry = AppRegistry()
125
+ registry.populate(settings.INSTALLED_APPS)
126
+ TORTOISE_ORM = build_tortoise_config(settings, registry)
127
+ """
128
+
129
+ URLS = """from fastapi import APIRouter
130
+
131
+ router = APIRouter()
132
+ """
133
+
134
+ ASGI = """import os
135
+
136
+ from fapilot import create_app
137
+ from fapilot.conf import load_settings
138
+
139
+ os.environ.setdefault("FAPILOT_SETTINGS_MODULE", "config.settings")
140
+ app = create_app(load_settings("config.settings"))
141
+ """
142
+
143
+ ENV = """DEBUG=true
144
+ SECRET_KEY=change-me
145
+ DATABASE_URL=sqlite://db.sqlite3
146
+ """
147
+
148
+ GITIGNORE = """.venv/
149
+ __pycache__/
150
+ .env
151
+ db.sqlite3
152
+ .ruff_cache/
153
+ .pytest_cache/
154
+ """
155
+
156
+ PROJECT_README = """# {name}
157
+
158
+ Generated by Fapilot.
159
+
160
+ ```bash
161
+ uv sync
162
+ fapilot startapp users
163
+ fapilot runserver
164
+ ```
165
+ """
166
+
167
+ PROJECT_PYPROJECT = '''[project]
168
+ name = "{name}"
169
+ version = "0.1.0"
170
+ requires-python = ">=3.12"
171
+ dependencies = ["fapilot"]
172
+
173
+ [tool.aerich]
174
+ tortoise_orm = "config.database.TORTOISE_ORM"
175
+ location = "./migrations"
176
+ src_folder = "."
177
+ '''
178
+
179
+ DOCKERFILE = """FROM python:3.12-slim
180
+ WORKDIR /app
181
+ COPY . .
182
+ RUN pip install fapilot
183
+ CMD ["uvicorn", "config.asgi:app", "--host", "0.0.0.0", "--port", "8000"]
184
+ """
185
+
186
+ COMPOSE = """services:
187
+ postgres:
188
+ image: postgres:16
189
+ environment:
190
+ POSTGRES_DB: app
191
+ POSTGRES_USER: app
192
+ POSTGRES_PASSWORD: app
193
+ ports:
194
+ - "5432:5432"
195
+ """
196
+
197
+ APP_FILES = {
198
+ "__init__.py": "",
199
+ "apps.py": """from fapilot.apps import AppConfig
200
+
201
+
202
+ class {class_name}Config(AppConfig):
203
+ def __init__(self) -> None:
204
+ super().__init__(name="apps.{name}", label="{name}")
205
+ """,
206
+ "models.py": "from tortoise import fields, models\n\n\n# Define models here.\n",
207
+ "schemas.py": "from pydantic import BaseModel, ConfigDict\n\n\n# Define schemas here.\n",
208
+ "api.py": """from fastapi import APIRouter
209
+
210
+ router = APIRouter()
211
+ """,
212
+ "services.py": "",
213
+ "repositories.py": "",
214
+ "permissions.py": "from fapilot.permissions import AllowAny, IsAuthenticated\n",
215
+ "dependencies.py": "",
216
+ "signals.py": "",
217
+ "admin.py": "",
218
+ }
@@ -0,0 +1,4 @@
1
+ from fapilot.conf.settings import FapilotSettings, get_settings, load_settings
2
+
3
+ __all__ = ["FapilotSettings", "get_settings", "load_settings"]
4
+
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import os
5
+ from functools import lru_cache
6
+ from typing import Any
7
+
8
+ from pydantic import Field, field_validator
9
+ from pydantic_settings import BaseSettings, SettingsConfigDict
10
+
11
+
12
+ class JWTSettings(BaseSettings):
13
+ algorithm: str = "HS256"
14
+ access_token_expire_minutes: int = 30
15
+ issuer: str = "fapilot"
16
+
17
+
18
+ class FapilotSettings(BaseSettings):
19
+ model_config = SettingsConfigDict(
20
+ env_file=".env",
21
+ env_nested_delimiter="__",
22
+ extra="ignore",
23
+ case_sensitive=True,
24
+ )
25
+
26
+ DEBUG: bool = False
27
+ SECRET_KEY: str = Field(default="change-me")
28
+ ALLOWED_HOSTS: list[str] = Field(default_factory=lambda: ["localhost", "127.0.0.1"])
29
+ DATABASE_URL: str = "sqlite://db.sqlite3"
30
+ INSTALLED_APPS: list[str] = Field(default_factory=list)
31
+ MIDDLEWARE: list[str] = Field(default_factory=list)
32
+ CORS_ALLOWED_ORIGINS: list[str] = Field(default_factory=list)
33
+ TIME_ZONE: str = "UTC"
34
+ LANGUAGE_CODE: str = "en-us"
35
+ API_PREFIX: str = "/api"
36
+ DEFAULT_PAGE_SIZE: int = 20
37
+ MAX_PAGE_SIZE: int = 100
38
+ AUTH_USER_MODEL: str = "users.User"
39
+ JWT_SETTINGS: JWTSettings = Field(default_factory=JWTSettings)
40
+ LOGGING: dict[str, Any] = Field(default_factory=dict)
41
+
42
+ @field_validator("DEBUG", mode="before")
43
+ @classmethod
44
+ def parse_debug(cls, value: Any) -> Any:
45
+ if isinstance(value, str) and value.lower() in {"release", "prod", "production"}:
46
+ return False
47
+ return value
48
+
49
+
50
+ def load_settings(settings_module: str | None = None) -> FapilotSettings:
51
+ module_name = settings_module or os.getenv("FAPILOT_SETTINGS_MODULE")
52
+ if module_name is None:
53
+ return FapilotSettings()
54
+ module = importlib.import_module(module_name)
55
+ values = {
56
+ key: getattr(module, key)
57
+ for key in dir(module)
58
+ if key.isupper() and not key.startswith("_")
59
+ }
60
+ return FapilotSettings(**values)
61
+
62
+
63
+ @lru_cache
64
+ def get_settings() -> FapilotSettings:
65
+ return load_settings()
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator, Callable
4
+ from contextlib import asynccontextmanager
5
+ from importlib import import_module
6
+
7
+ from fastapi import FastAPI
8
+
9
+ from fapilot.apps import AppRegistry
10
+ from fapilot.conf import FapilotSettings, get_settings
11
+ from fapilot.db.tortoise import close_orm, init_orm
12
+ from fapilot.events.dispatcher import SignalDispatcher
13
+
14
+
15
+ class Fapilot:
16
+ def __init__(self, settings: FapilotSettings | None = None) -> None:
17
+ self.settings = settings or get_settings()
18
+ self.registry = AppRegistry()
19
+ self.events = SignalDispatcher()
20
+
21
+ def setup(self) -> None:
22
+ self.registry.populate(self.settings.INSTALLED_APPS)
23
+
24
+ def create_fastapi(self) -> FastAPI:
25
+ self.setup()
26
+
27
+ @asynccontextmanager
28
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
29
+ app.state.fapilot = self
30
+ await init_orm(self.settings, self.registry)
31
+ await self.events.emit("startup", app=app)
32
+ try:
33
+ yield
34
+ finally:
35
+ await self.events.emit("shutdown", app=app)
36
+ await close_orm()
37
+
38
+ app = FastAPI(debug=self.settings.DEBUG, lifespan=lifespan)
39
+ app.state.fapilot = self
40
+ self._install_middleware(app)
41
+ self._include_app_routers(app)
42
+ return app
43
+
44
+ def _install_middleware(self, app: FastAPI) -> None:
45
+ for dotted_path in self.settings.MIDDLEWARE:
46
+ factory = import_string(dotted_path)
47
+ factory(app)
48
+
49
+ def _include_app_routers(self, app: FastAPI) -> None:
50
+ for app_config in self.registry.get_apps():
51
+ router = app_config.router
52
+ if router is None:
53
+ try:
54
+ api_module = import_module(f"{app_config.name}.api")
55
+ except ModuleNotFoundError:
56
+ continue
57
+ router = getattr(api_module, "router", None)
58
+ if router is not None:
59
+ prefix = (
60
+ app_config.router_prefix
61
+ or f"{self.settings.API_PREFIX}/{app_config.app_label}"
62
+ )
63
+ app.include_router(router, prefix=prefix, tags=[app_config.app_label])
64
+
65
+
66
+ def import_string(dotted_path: str) -> Callable:
67
+ module_path, _, attribute = dotted_path.rpartition(".")
68
+ if not module_path:
69
+ raise ImportError(f"{dotted_path!r} is not a dotted import path")
70
+ module = import_module(module_path)
71
+ return getattr(module, attribute)
72
+
73
+
74
+ def create_app(settings: FapilotSettings | None = None) -> FastAPI:
75
+ return Fapilot(settings=settings).create_fastapi()
fapilot/crud.py ADDED
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Generic, TypeVar
4
+
5
+ from pydantic import BaseModel
6
+ from tortoise.models import Model
7
+
8
+ ModelT = TypeVar("ModelT", bound=Model)
9
+ CreateSchemaT = TypeVar("CreateSchemaT", bound=BaseModel)
10
+ UpdateSchemaT = TypeVar("UpdateSchemaT", bound=BaseModel)
11
+
12
+
13
+ class CRUDRouterService(Generic[ModelT, CreateSchemaT, UpdateSchemaT]):
14
+ def __init__(self, model: type[ModelT]) -> None:
15
+ self.model = model
16
+
17
+ async def list(
18
+ self,
19
+ *,
20
+ offset: int = 0,
21
+ limit: int = 20,
22
+ filters: dict[str, Any] | None = None,
23
+ ):
24
+ queryset = self.model.filter(**(filters or {}))
25
+ return await queryset.offset(offset).limit(limit)
26
+
27
+ async def count(self, filters: dict[str, Any] | None = None) -> int:
28
+ return await self.model.filter(**(filters or {})).count()
29
+
30
+ async def get(self, object_id: Any) -> ModelT | None:
31
+ return await self.model.get_or_none(id=object_id)
32
+
33
+ async def create(self, data: CreateSchemaT) -> ModelT:
34
+ return await self.model.create(**data.model_dump())
35
+
36
+ async def update(self, instance: ModelT, data: UpdateSchemaT) -> ModelT:
37
+ for key, value in data.model_dump(exclude_unset=True).items():
38
+ setattr(instance, key, value)
39
+ await instance.save()
40
+ return instance
41
+
42
+ async def delete(self, instance: ModelT) -> None:
43
+ await instance.delete()
fapilot/db/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from fapilot.db.migrations import AerichMigrationBackend, MigrationBackend
2
+
3
+ __all__ = ["AerichMigrationBackend", "MigrationBackend"]
4
+
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ from abc import ABC, abstractmethod
5
+ from dataclasses import dataclass
6
+
7
+
8
+ class MigrationBackend(ABC):
9
+ @abstractmethod
10
+ def init(self) -> None: ...
11
+
12
+ @abstractmethod
13
+ def makemigrations(self, name: str | None = None) -> None: ...
14
+
15
+ @abstractmethod
16
+ def migrate(self) -> None: ...
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class AerichMigrationBackend(MigrationBackend):
21
+ config: str = "pyproject.toml"
22
+ app: str = "models"
23
+ tortoise_config_path: str = "config.database.TORTOISE_ORM"
24
+
25
+ def init(self) -> None:
26
+ self._run("init", "-t", self.tortoise_config_path)
27
+
28
+ def makemigrations(self, name: str | None = None) -> None:
29
+ args = ["migrate"]
30
+ if name:
31
+ args.extend(["--name", name])
32
+ self._run(*args)
33
+
34
+ def migrate(self) -> None:
35
+ self._run("upgrade")
36
+
37
+ def _run(self, *args: str) -> None:
38
+ subprocess.run(
39
+ ["aerich", "-c", self.config, "--app", self.app, *args],
40
+ check=True,
41
+ )
42
+
fapilot/db/tortoise.py ADDED
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ from tortoise import Tortoise
4
+
5
+ from fapilot.apps import AppRegistry
6
+ from fapilot.conf import FapilotSettings
7
+
8
+
9
+ def build_tortoise_config(settings: FapilotSettings, registry: AppRegistry) -> dict:
10
+ apps: dict[str, dict] = {
11
+ "models": {"models": ["aerich.models"], "default_connection": "default"}
12
+ }
13
+ for app_config in registry.get_apps():
14
+ models = [f"{app_config.name}.models"]
15
+ models.extend(app_config.tortoise_models)
16
+ apps[app_config.app_label] = {"models": models, "default_connection": "default"}
17
+ return {"connections": {"default": settings.DATABASE_URL}, "apps": apps}
18
+
19
+
20
+ async def init_orm(settings: FapilotSettings, registry: AppRegistry) -> None:
21
+ await Tortoise.init(config=build_tortoise_config(settings, registry))
22
+ if settings.DEBUG:
23
+ await Tortoise.generate_schemas(safe=True)
24
+
25
+
26
+ async def close_orm() -> None:
27
+ await Tortoise.close_connections()
28
+
@@ -0,0 +1,4 @@
1
+ from fapilot.events.dispatcher import SignalDispatcher
2
+
3
+ __all__ = ["SignalDispatcher"]
4
+
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections import defaultdict
5
+ from collections.abc import Awaitable, Callable
6
+ from typing import Any
7
+
8
+ Receiver = Callable[..., Awaitable[None] | None]
9
+
10
+
11
+ class SignalDispatcher:
12
+ def __init__(self) -> None:
13
+ self._receivers: dict[str, list[Receiver]] = defaultdict(list)
14
+
15
+ def connect(self, signal: str, receiver: Receiver) -> None:
16
+ self._receivers[signal].append(receiver)
17
+
18
+ async def emit(self, signal: str, **payload: Any) -> None:
19
+ for receiver in self._receivers.get(signal, []):
20
+ result = receiver(**payload)
21
+ if inspect.isawaitable(result):
22
+ await result
23
+
fapilot/exceptions.py ADDED
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class FapilotError(Exception):
5
+ pass
6
+
7
+
8
+ class ConfigurationError(FapilotError):
9
+ pass
10
+
fapilot/filtering.py ADDED
@@ -0,0 +1,8 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ def pick_filters(params: dict[str, Any], allowed: set[str]) -> dict[str, Any]:
7
+ return {key: value for key, value in params.items() if key in allowed and value is not None}
8
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+
5
+
6
+ class CommandRegistry:
7
+ def __init__(self) -> None:
8
+ self._commands: dict[str, Callable[..., None]] = {}
9
+
10
+ def register(self, name: str, command: Callable[..., None]) -> None:
11
+ self._commands[name] = command
12
+
13
+ def get(self, name: str) -> Callable[..., None]:
14
+ return self._commands[name]
15
+
fapilot/middleware.py ADDED
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import FastAPI
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+
6
+ from fapilot.conf import get_settings
7
+
8
+
9
+ def install_cors(app: FastAPI) -> None:
10
+ settings = get_settings()
11
+ if settings.CORS_ALLOWED_ORIGINS:
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=settings.CORS_ALLOWED_ORIGINS,
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
fapilot/pagination.py ADDED
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Generic, TypeVar
5
+
6
+ from fastapi import Depends, Query
7
+ from pydantic import BaseModel
8
+
9
+ from fapilot.conf import get_settings
10
+
11
+ T = TypeVar("T")
12
+
13
+
14
+ class Page(BaseModel, Generic[T]):
15
+ items: Sequence[T]
16
+ total: int
17
+ limit: int
18
+ offset: int
19
+
20
+
21
+ class LimitOffset(BaseModel):
22
+ limit: int
23
+ offset: int
24
+
25
+
26
+ def pagination_params(
27
+ limit: int | None = Query(default=None, ge=1),
28
+ offset: int = Query(default=0, ge=0),
29
+ ) -> LimitOffset:
30
+ settings = get_settings()
31
+ chosen_limit = limit or settings.DEFAULT_PAGE_SIZE
32
+ return LimitOffset(limit=min(chosen_limit, settings.MAX_PAGE_SIZE), offset=offset)
33
+
34
+
35
+ Pagination = Depends(pagination_params)
@@ -0,0 +1,4 @@
1
+ from fapilot.permissions.base import AllowAny, IsAuthenticated, Permission
2
+
3
+ __all__ = ["AllowAny", "IsAuthenticated", "Permission"]
4
+
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Protocol
4
+
5
+ from fastapi import HTTPException, Request, status
6
+
7
+
8
+ class Permission(Protocol):
9
+ async def has_permission(self, request: Request) -> bool: ...
10
+
11
+
12
+ class AllowAny:
13
+ async def has_permission(self, request: Request) -> bool:
14
+ return True
15
+
16
+
17
+ class IsAuthenticated:
18
+ async def has_permission(self, request: Request) -> bool:
19
+ return getattr(request.state, "user", None) is not None
20
+
21
+
22
+ async def require_permissions(request: Request, *permissions: Permission) -> None:
23
+ for permission in permissions:
24
+ if not await permission.has_permission(request):
25
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Permission denied")
26
+
fapilot/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,5 @@
1
+ from fapilot.realtime.sse import EventSourceResponse, sse_event
2
+ from fapilot.realtime.websockets import WebSocketHub
3
+
4
+ __all__ = ["EventSourceResponse", "WebSocketHub", "sse_event"]
5
+
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import AsyncIterable
5
+ from typing import Any
6
+
7
+ from starlette.responses import StreamingResponse
8
+
9
+
10
+ def sse_event(data: Any, *, event: str | None = None, event_id: str | None = None) -> str:
11
+ lines: list[str] = []
12
+ if event_id:
13
+ lines.append(f"id: {event_id}")
14
+ if event:
15
+ lines.append(f"event: {event}")
16
+ payload = data if isinstance(data, str) else json.dumps(data)
17
+ for line in payload.splitlines():
18
+ lines.append(f"data: {line}")
19
+ return "\n".join(lines) + "\n\n"
20
+
21
+
22
+ class EventSourceResponse(StreamingResponse):
23
+ def __init__(self, content: AsyncIterable[str]) -> None:
24
+ super().__init__(content, media_type="text/event-stream")
25
+
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import WebSocket
4
+
5
+
6
+ class WebSocketHub:
7
+ def __init__(self) -> None:
8
+ self.connections: set[WebSocket] = set()
9
+
10
+ async def connect(self, websocket: WebSocket) -> None:
11
+ await websocket.accept()
12
+ self.connections.add(websocket)
13
+
14
+ def disconnect(self, websocket: WebSocket) -> None:
15
+ self.connections.discard(websocket)
16
+
17
+ async def broadcast_text(self, message: str) -> None:
18
+ stale: list[WebSocket] = []
19
+ for websocket in self.connections:
20
+ try:
21
+ await websocket.send_text(message)
22
+ except RuntimeError:
23
+ stale.append(websocket)
24
+ for websocket in stale:
25
+ self.disconnect(websocket)
26
+
fapilot/responses.py ADDED
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from fastapi.responses import JSONResponse
6
+
7
+
8
+ def ok(data: Any = None, *, status_code: int = 200) -> JSONResponse:
9
+ return JSONResponse({"data": data}, status_code=status_code)
10
+
@@ -0,0 +1,4 @@
1
+ from fapilot.testing.client import AsyncTestClient
2
+
3
+ __all__ = ["AsyncTestClient"]
4
+
@@ -0,0 +1,17 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator
4
+ from contextlib import asynccontextmanager
5
+
6
+ from fastapi import FastAPI
7
+ from httpx import ASGITransport, AsyncClient
8
+
9
+
10
+ @asynccontextmanager
11
+ async def AsyncTestClient(app: FastAPI) -> AsyncIterator[AsyncClient]:
12
+ async with AsyncClient(
13
+ transport=ASGITransport(app=app),
14
+ base_url="http://testserver",
15
+ ) as client:
16
+ yield client
17
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fapilot maintainers
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,134 @@
1
+ Metadata-Version: 2.2
2
+ Name: fapilot
3
+ Version: 0.1.0
4
+ Summary: A Django-inspired async application framework built on FastAPI, Tortoise ORM, and Aerich.
5
+ Author: Ali Hajiali
6
+ Maintainer: Ali Hajiali
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/alihajiali/fapilot
9
+ Project-URL: Repository, https://github.com/alihajiali/fapilot
10
+ Project-URL: Issues, https://github.com/alihajiali/fapilot/issues
11
+ Project-URL: Changelog, https://github.com/alihajiali/fapilot/blob/main/CHANGELOG.md
12
+ Keywords: fastapi,async,framework,tortoise-orm,aerich,django-inspired
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.12
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: fastapi<0.142,>=0.141
30
+ Requires-Dist: starlette<0.50,>=0.49
31
+ Requires-Dist: pydantic<3,>=2.12
32
+ Requires-Dist: pydantic-settings<3,>=2.10
33
+ Requires-Dist: tortoise-orm[asyncpg]<1.2,>=1.1
34
+ Requires-Dist: aerich[toml]<0.11,>=0.10
35
+ Requires-Dist: uvicorn[standard]<0.36,>=0.35
36
+ Requires-Dist: python-jose<4,>=3.5
37
+ Requires-Dist: passlib[bcrypt]<2,>=1.7
38
+ Requires-Dist: python-multipart<0.0.21,>=0.0.20
39
+ Provides-Extra: dev
40
+ Requires-Dist: build<2,>=1.3; extra == "dev"
41
+ Requires-Dist: pytest<9,>=8.4; extra == "dev"
42
+ Requires-Dist: pytest-anyio>=0.0.0; extra == "dev"
43
+ Requires-Dist: httpx<0.29,>=0.28; extra == "dev"
44
+ Requires-Dist: ruff<0.13,>=0.12; extra == "dev"
45
+ Requires-Dist: pyright<2,>=1.1; extra == "dev"
46
+ Requires-Dist: twine<7,>=6.2; extra == "dev"
47
+
48
+ # Fapilot
49
+
50
+ Fapilot is an opinionated, async-first backend framework built on FastAPI. It borrows Django's project organization, app registry, settings discipline, scaffolding, and management-command ergonomics while keeping FastAPI's dependency injection, OpenAPI, lifespan, and async runtime model.
51
+
52
+ ## Features
53
+
54
+ - Django-inspired project and app scaffolding.
55
+ - FastAPI application factory with app registry integration.
56
+ - Pydantic settings loader with uppercase application settings.
57
+ - Tortoise ORM configuration and Aerich migration backend.
58
+ - Pagination, filtering, CRUD, permissions, middleware, events, auth, and realtime helpers.
59
+ - CLI commands for project creation, app creation, migrations, and local serving.
60
+
61
+ ## Installation
62
+
63
+ For local development from this repository:
64
+
65
+ ```bash
66
+ python3.12 -m venv .venv
67
+ source .venv/bin/activate
68
+ python -m pip install -U pip
69
+ python -m pip install -e ".[dev]"
70
+ ```
71
+
72
+ After installation, the `fapilot` command is available on your shell path:
73
+
74
+ ```bash
75
+ fapilot --help
76
+ ```
77
+
78
+ You can also run the CLI directly from a checkout:
79
+
80
+ ```bash
81
+ python3.12 -m fapilot.cli --help
82
+ ```
83
+
84
+ ## Quick Start
85
+
86
+ ```bash
87
+ python3.12 -m pip install -e .
88
+ fapilot startproject myproject
89
+ cd myproject
90
+ fapilot startapp users
91
+ fapilot makemigrations
92
+ fapilot migrate
93
+ fapilot runserver
94
+ ```
95
+
96
+ Core stack:
97
+
98
+ - FastAPI + Starlette lifespan
99
+ - Pydantic v2 + pydantic-settings
100
+ - Tortoise ORM
101
+ - Aerich migrations through a backend abstraction
102
+ - Uvicorn
103
+ - pytest, HTTPX, AnyIO
104
+ - Ruff and Pyright
105
+
106
+ This repository contains the reusable framework package. Generated projects contain `config/`, `apps/`, `common/`, `manage.py`, Docker files, `.env`, and a project-local `pyproject.toml`.
107
+
108
+ ## CLI
109
+
110
+ ```bash
111
+ fapilot startproject myproject
112
+ fapilot startapp users
113
+ fapilot makemigrations --name initial
114
+ fapilot migrate
115
+ fapilot runserver --host 127.0.0.1 --port 8000
116
+ ```
117
+
118
+ ## Development
119
+
120
+ ```bash
121
+ ruff check .
122
+ pyright
123
+ pytest
124
+ python -m build
125
+ twine check dist/*
126
+ ```
127
+
128
+ ## Release
129
+
130
+ See [RELEASE.md](RELEASE.md) for the release checklist and PyPI publishing flow.
131
+
132
+ ## License
133
+
134
+ Fapilot is released under the MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,40 @@
1
+ fapilot/__init__.py,sha256=J6rLlmU-8CEoeiHp-rKZ5I25Gv9JlqT-2piWIkrgpmA,132
2
+ fapilot/cli.py,sha256=MbTHduI2zOh8nR_psTb36_aDKx10hFk54Js495MvIJQ,6439
3
+ fapilot/crud.py,sha256=F_lcVzEZqpm7MfpgYBbNGSKWiF6Zp4UikeX4gZyjRFo,1427
4
+ fapilot/exceptions.py,sha256=qGDMYEt_1TcKTfiJP7RnHMy5TVY4gbyCzSUB4bR1_Ew,129
5
+ fapilot/filtering.py,sha256=LZqbpRDj6L36v6YVo2PtPT5pa5isa7PKVtFBxdRmU-A,238
6
+ fapilot/middleware.py,sha256=JlyEjCBI64805zYf5unll1kp0tuHBwlDH3hucrgCz8s,490
7
+ fapilot/pagination.py,sha256=dtpqjsn4RKROK-ZarPwWDhn-D0uI8tFhps2xawPMta8,752
8
+ fapilot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
9
+ fapilot/responses.py,sha256=hXdS6MbonAqrpJGfk_BR606g-4HqTkW9Phh9rv2WCZ8,240
10
+ fapilot/apps/__init__.py,sha256=_S4pBcO7UkREcPm2Gf6GP7rf25GX2Ua4Sh-ENO60y6I,129
11
+ fapilot/apps/config.py,sha256=ztb5yJcgSLBrlNWJZhvukc7LP93KXTrjUB0V-ionWvg,891
12
+ fapilot/apps/registry.py,sha256=1fmG8cu7Z13sk76k5hW46sgfhRjG7jlYxsTCH0LSVnM,1454
13
+ fapilot/auth/__init__.py,sha256=N-hLFiXPvRam2vxVsHXJbrHawnrYv2L8VSN9Fyi_O9s,231
14
+ fapilot/auth/jwt.py,sha256=K_ef4PUbNTlXLaXl1oFqgP0baackzFJz42jEpJ_EcpI,896
15
+ fapilot/auth/passwords.py,sha256=Ng5x3xJY_HBU0x1iPEUC6d0SLAtpK6iGUxFlQatf4a8,351
16
+ fapilot/background/__init__.py,sha256=awrJ0Uhf3DgOlqf_c0sGdJUTIn7FyeLEJRbggRetUYU,73
17
+ fapilot/background/tasks.py,sha256=Qqctpmkr-HuKiTBTOYoQfeXwcHt4B_uyZbOgHWwhlRI,349
18
+ fapilot/conf/__init__.py,sha256=OiHubavsDToAvPsS2ENYCGULjj2t1R5yiqkyVNpK7NI,144
19
+ fapilot/conf/settings.py,sha256=FJmgdb_u4cOeKL1ImpfkNZOFTHKTTZWN26J9VF66H70,2023
20
+ fapilot/core/application.py,sha256=tN-fH06ejjiMmbsQ_DxHaAlAow30g4n6CdyUAGDAMvU,2660
21
+ fapilot/db/__init__.py,sha256=uuM0ctHBQEHdDv916FbjyinB00KoOGlzp4G2kglg3Wk,134
22
+ fapilot/db/migrations.py,sha256=IKiaerTaACGQkYx7dxrpxgY63AvzSvNTsiVtt5wWUWo,1039
23
+ fapilot/db/tortoise.py,sha256=WZan7hTZCf8YNR7pGiHlwpdrqzSsRVrcawD50r7Ldsc,956
24
+ fapilot/events/__init__.py,sha256=_0HZCJcleKYxMaSJZ_gZ-T9RxsMw85-nhb75tN3vxR4,88
25
+ fapilot/events/dispatcher.py,sha256=_1nZpudAUpc-OlWsLAxJ78GSrvWjX_zN7kg53yZGjWg,687
26
+ fapilot/management/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
27
+ fapilot/management/commands.py,sha256=W72PqEMwPgGik3qJp3eIS0DvCnvjhC8clFQnVoYTkGM,394
28
+ fapilot/permissions/__init__.py,sha256=xL820vD0TBpKhlN5V6oF06OkXjVZvKA5Afw166d5zQI,133
29
+ fapilot/permissions/base.py,sha256=4EwcXN8MVxpw39q8DMpeED6z2-2FlJyAiqhjY38ld4o,740
30
+ fapilot/realtime/__init__.py,sha256=DDw_AyPOg1rtS0nqZPNbXW4755hMWoyjJoXzzAffryU,182
31
+ fapilot/realtime/sse.py,sha256=RfrahRxsYevY3iLwgY03rlf8kquazERaiATsXiToMN0,749
32
+ fapilot/realtime/websockets.py,sha256=RjGwp7uAoDgFsVezGV-gCw2jcS5HcstADa5LrmVP7fE,754
33
+ fapilot/testing/__init__.py,sha256=ITVn2wFLGLrAFRLHkyfz7-Wvvzx41nXEgHbj_enSc4Y,83
34
+ fapilot/testing/client.py,sha256=8-EegMiU76rN_LYCxtweNoB6L4MyuEKQOkDRoEJRUsw,436
35
+ fapilot-0.1.0.dist-info/LICENSE,sha256=htg2Bz7VZtqVFWWuLBWnUbYEGqvYbv77drVoMIvfjBg,1076
36
+ fapilot-0.1.0.dist-info/METADATA,sha256=-WQw5ZBJ7XeUy_IzOGp8HWxj2Sjq2gaZYwhMnvZ4TYU,4133
37
+ fapilot-0.1.0.dist-info/WHEEL,sha256=beeZ86-EfXScwlR_HKu4SllMC9wUEj_8Z_4FJ3egI2w,91
38
+ fapilot-0.1.0.dist-info/entry_points.txt,sha256=3K-ijMOGboG4CBmMD2HKvYly7qtxl_jkc7Ax4mCNkwc,45
39
+ fapilot-0.1.0.dist-info/top_level.txt,sha256=Mu-7cNCqmfAlxqaeV6daEf2V4neAxQS1BQZAOMX3SLc,8
40
+ fapilot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (76.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fapilot = fapilot.cli:main
@@ -0,0 +1 @@
1
+ fapilot