python-fastapi-best-practices-cursorrules-prompt-f — правило
Правило Cursor, которое задаёт агенту стиль кода для Python и FastAPI: функциональный подход, Pydantic v2, async-операции.
.cursor/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdcЧто делает python-fastapi-best-practices-cursorrules-prompt-f
Правило подключается к Cursor и подсказывает агенту, как писать код в проекте на FastAPI. Внутри — набор договорённостей: функциональный и декларативный стиль, классы только там, где без них не обойтись, модульность вместо копирования кода. Имена переменных с вспомогательными глаголами вроде is_active или has_permission, файлы и папки в нижнем регистре через подчёркивание, например routers/user_routes.py.
Отдельно описана работа с данными и ошибками. Для валидации входа и схем ответа берутся модели Pydantic, а не сырые словари. Ожидаемые ошибки возвращаются через HTTPException с конкретными HTTP-ответами, неожиданные ловит middleware вместе с логированием. Блокирующий ввод-вывод сводится к минимуму: все обращения к базе и внешним API — асинхронные.
Правило ждёт от проекта FastAPI, Pydantic v2 и асинхронной библиотеки для базы вроде asyncpg или aiomysql, а при работе через ORM — SQLAlchemy 2.0. Если у вас Pydantic v1, часть советов про схемы придётся перепроверять вручную. События старта и остановки приложения правило советует переносить на lifespan-контексты вместо @app.on_event.
Какие задачи решает
- задать агенту единый стиль кода для FastAPI-проекта
- перевести валидацию входа на модели Pydantic вместо словарей
- убрать блокирующие вызовы базы из обработчиков
- заменить устаревшие обработчики startup и shutdown на lifespan
- разложить роутеры и утилиты по понятной структуре файлов
Примеры запросов агенту
- Напиши роутер для пользователей: async def, type hints, схемы на Pydantic v2
- Переделай эти обработчики на lifespan вместо @app.on_event
- Проверь модуль на блокирующий ввод-вывод и предложи асинхронный вариант
Как установить python-fastapi-best-practices-cursorrules-prompt-f
Вручную: положить файлы
.cursor/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/python-fastapi-best-practices-cursorrules-prompt-f.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdВручную: положить файлы
.clinerules/python-fastapi-best-practices-cursorrules-prompt-f.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Из того же набора68
Похожие
Рядом в теме «Бэкенд и API»
Всё по теме «Бэкенд и API» →Вопросы о python-fastapi-best-practices-cursorrules-prompt-f
Как установить правило python-fastapi-best-practices-cursorrules-prompt-f в Cursor?
Создайте файл .cursor/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdc в корне проекта и вставьте в него текст правила.
Что делает это правило?
Оно задаёт агенту Cursor стиль разработки на Python и FastAPI: функциональные компоненты, модели Pydantic для валидации, async для операций ввода-вывода и обработку ошибок через HTTPException.
Какие версии библиотек нужны для работы правила?
Правило рассчитано на FastAPI, Pydantic v2 и асинхронные библиотеки вроде asyncpg или aiomysql; при использовании ORM — SQLAlchemy 2.0.
Исходный текст
python-fastapi-best-practices-cursorrules-prompt-f.mdc · CC0-1.0
---
description: "Cursor rules for Python FastAPI development with best practices."
globs: **/*
alwaysApply: false
---
You are an expert in Python, FastAPI, and scalable API development.
Write concise, technical responses with accurate Python examples. Use functional, declarative programming; avoid classes where possible. Prefer iteration and modularization over code duplication. Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission). Use lowercase with underscores for directories and files (e.g., routers/user_routes.py). Favor named exports for routes and utility functions. Use the Receive an Object, Return an Object (RORO) pattern. Use def for pure functions and async def for asynchronous operations. Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
Avoid unnecessary curly braces in conditional statements. For single-line statements in conditionals, omit curly braces. Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).
Prioritize error handling and edge cases:
FastAPI
Pydantic v2
Async database libraries like asyncpg or aiomysql
SQLAlchemy 2.0 (if using ORM features)
Use functional components (plain functions) and Pydantic models for input validation and response schemas. Use declarative route definitions with clear return type annotations. Use def for synchronous operations and async def for asynchronous ones. Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events. Use middleware for logging, error monitoring, and performance optimization. Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading. Use HTTPException for expected errors and model them as specific HTTP responses. Use middleware for handling unexpected errors, logging, and error monitoring. Use Pydantic's BaseModel for consistent input/output validation and response schemas. Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests. Implement caching for static and frequently accessed data using tools like Redis or in-memory stores. Optimize data serialization and deserialization with Pydantic. Use lazy loading techniques for large datasets and substantial API responses. Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules