Logo Web Application

Web Application

Tổ chức
ludo-technologies
web-application

FastAPI web application best practices covering authentication and authorization, SQLAlchemy 2.0 async sessions, transactions, eager loading, and Alembic migrations, non-blocking I/O and shared HTTP clients, request/response schemas, error responses, pagination, typed settings, app factory and lifespan, request-ID logging, and endpoint testing. Use when building, reviewing, or refactoring a FastAPI backend or REST API, or code that touches SQLAlchemy, Alembic, authentication, or HTTP endpoints. Not for Django or Flask projects.

Tổng quan

Nhà phát hànhludo-technologies
Kho mãpython-best-practices
Tên kỹ năngweb-application
Sao
36
Bản fork
6
Tệp đi kèm
25
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 25 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được ludo-technologies công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Web Application trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/ludo-technologies/python-best-practices/tree/main/skills/web-application
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ludo-technologies/python-best-practices.git /tmp/python-best-practices
mkdir -p .claude/skills
cp -r /tmp/python-best-practices/skills/web-application .claude/skills/web-application
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Web Application trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Web Application ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Web Application không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Python Web Application

Best practices for FastAPI backends. Designed for AI agents and LLMs to build web applications that are secure, correct under concurrency, and testable.

The rules assume one stack: FastAPI, SQLAlchemy 2.0 (async), Alembic, Pydantic v2 with pydantic-settings, httpx, PyJWT, and pwdlib. Examples use the async stack; the same rules apply to sync def endpoints with Session. Django and Flask are out of scope. Where a rule overlaps a coding-standards or testing rule, this skill takes precedence for web application code.

All examples share one invoice application. Its models are defined in db-sqlalchemy-2-style, its Settings in config-typed-settings, and its create_app in app-factory-lifespan; other rules show only the part they discuss. Read the matching rule file in full before writing code in its area.

Categories

Security [CRITICAL]

Authenticate users safely and authorize every access to their data.

RuleDescription
sec-password-hashingHash passwords with Argon2
sec-secure-tokensGenerate tokens with secrets and compare in constant time
sec-jwt-validationValidate JWTs with a pinned algorithm and required claims
sec-object-authorizationAuthorize access to every object, not just the endpoint
sec-cors-originsList allowed CORS origins explicitly

Database [CRITICAL]

Query, scope, and evolve the database safely with SQLAlchemy 2.0 and Alembic.

RuleDescription
db-parameterized-queriesNever build SQL with string formatting
db-session-per-requestCreate the engine once and a session per request
db-transaction-boundaryCommit once per use case, not in helpers or dependency teardown
db-eager-loadingLoad relationships explicitly and make lazy loads raise
db-migrations-alembicChange the schema with Alembic migrations
db-sqlalchemy-2-styleUse SQLAlchemy 2.0 typed models and select()

Async I/O [CRITICAL]

Keep the event loop free so one request cannot stall the others.

RuleDescription
async-no-blocking-callsNever block the event loop in async def endpoints
async-shared-http-clientShare one httpx.AsyncClient with explicit timeouts

API Design [HIGH]

Shape what enters and leaves the API.

RuleDescription
api-separate-schemasSeparate request and response models from ORM models
api-error-responsesMap domain errors to HTTP responses in exception handlers
api-bounded-listsBound and paginate every list endpoint

Configuration [HIGH]

Fail at startup, not at the first request, when configuration is wrong.

RuleDescription
config-typed-settingsLoad configuration into a typed settings object at startup

App Structure [HIGH]

Compose the app explicitly so resources and logic are replaceable and testable.

RuleDescription
app-factory-lifespanBuild the app in a factory and manage resources in lifespan
app-thin-routesKeep route functions thin and inject dependencies with Annotated

Observability [MEDIUM]

Make each request traceable through the logs.

RuleDescription
obs-request-id-loggingCorrelate logs with a request ID

Testing [MEDIUM]

Test through the real app and a real database.

RuleDescription
test-dependency-overridesTest endpoints with dependency_overrides, not patching
test-db-rollbackRun tests against a real database in a rolled-back transaction

Quick Reference

App Factory and Dependencies

python
def create_app(settings: Settings) -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        engine = create_async_engine(
            settings.database_url.get_secret_value(), pool_pre_ping=True
        )
        try:
            async with httpx.AsyncClient(
                base_url=settings.payments_base_url,
                timeout=httpx.Timeout(10.0, connect=3.0),
            ) as payments_client:
                app.state.sessionmaker = async_sessionmaker(
                    engine, expire_on_commit=False
                )
                app.state.payments_client = payments_client
                yield
        finally:
            await engine.dispose()

    app = FastAPI(lifespan=lifespan)
    app.state.settings = settings
    add_exception_handlers(app)
    app.include_router(invoices.router)
    return app


async def get_session(request: Request) -> AsyncIterator[AsyncSession]:
    async with request.app.state.sessionmaker() as session:
        yield session  # no commit here: teardown runs after the response is sent


SessionDep = Annotated[AsyncSession, Depends(get_session)]
CurrentUser = Annotated[User, Depends(get_current_user)]

Authorized, Eager-Loaded Query

python
router = APIRouter(prefix="/invoices", dependencies=[Depends(get_current_user)])


@router.get("/{invoice_id}")
async def read_invoice(
    invoice_id: int, user: CurrentUser, session: SessionDep
) -> InvoiceRead:
    invoice = await session.scalar(
        select(Invoice)
        .where(Invoice.id == invoice_id, Invoice.owner_id == user.id)  # scoped by owner
        .options(selectinload(Invoice.lines))  # relationships declared lazy="raise"
    )
    if invoice is None:
        raise NotFoundError("Invoice")  # mapped to 404 by an exception handler
    return InvoiceRead.model_validate(invoice)

Passwords and Tokens

python
password_hash = PasswordHash.recommended()  # Argon2id via pwdlib
hashed = await asyncio.to_thread(password_hash.hash, password)

claims = jwt.decode(
    token,
    settings.jwt_secret.get_secret_value(),
    algorithms=["HS256"],
    audience=settings.jwt_audience,
    issuer=settings.jwt_issuer,
    options={"require": ["exp", "iat", "sub", "iss", "aud"]},
)

reset_token = secrets.token_urlsafe(32)  # store only its SHA-256 hash
hmac.compare_digest(expected_signature.encode(), presented_signature.encode())

Settings and CORS

python
class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="APP_")

    database_url: SecretStr
    jwt_secret: SecretStr = Field(min_length=32)
    jwt_issuer: str
    jwt_audience: str
    access_token_ttl_minutes: int = Field(default=15, gt=0, le=60)
    cors_origins: list[str] = []
    payments_base_url: str
    payments_api_key: SecretStr


app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,  # never ["*"] with allow_credentials=True
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

Testing

python
@pytest.fixture
async def session(engine: AsyncEngine) -> AsyncIterator[AsyncSession]:
    async with engine.connect() as conn:
        transaction = await conn.begin()
        session = AsyncSession(
            bind=conn, join_transaction_mode="create_savepoint", expire_on_commit=False
        )
        try:
            yield session
        finally:
            await session.close()
            await transaction.rollback()


@pytest.fixture
async def client(
    session: AsyncSession, settings: Settings
) -> AsyncIterator[httpx.AsyncClient]:
    app = create_app(settings)

    async def override_session() -> AsyncIterator[AsyncSession]:
        yield session

    app.dependency_overrides[get_session] = override_session
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        yield client

See Also

  • coding-standards - General Python rules; validation-pydantic, design-dependency-injection, design-no-global-singleton, and error-no-silent-exceptions underlie several rules here
  • testing - pytest structure, fixtures, and mocking that endpoint tests still follow
  • tooling - ruff, mypy, and pytest configuration; ruff's S rules catch several issues covered here

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Web Application làm được gì?

FastAPI web application best practices covering authentication and authorization, SQLAlchemy 2.0 async sessions, transactions, eager loading, and Alembic migrations, non-blocking I/O and shared HTTP clients, request/response schemas, error responses, pagination, typed settings, app factory and lifespan, request-ID logging, and endpoint testing. Use when building, reviewing, or refactoring a FastAPI backend or REST API, or code that touches SQLAlchemy, Alembic, authentication, or HTTP endpoints. Not for Django or Flask projects.

Vì sao nên dùng Web Application trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Web Application là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Web Application trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/ludo-technologies/python-best-practices/tree/main/skills/web-application. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Web Application?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Web Application với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Web Application với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Web Application có miễn phí không?

Có. Kỹ năng này được ludo-technologies phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇