python — правило для Cursor: стандарты Python, Flask и SQLite
Правило Cursor задаёт структуру проекта, стиль кода и типовые решения для Python с Flask и SQLite. Пригодится, когда агент пишет код в вашем репозитории.
.cursor/rules/python.mdcЧто делает python
Это файл правил для Cursor, который подключается к проекту как .cursor/rules/python.mdc. Он срабатывает на файлы по маске **/*.py, src/**/*.py, tests/**/*.py, поэтому советы приходят именно тогда, когда агент трогает Python-код. Автоприменение выключено: правило подгружается по совпадению с файлами, а не висит в контексте постоянно.
Внутри — набор договорённостей по проекту и коду. Структура: раскладка src/your_package_name/, тесты в tests/ рядом с src/, конфигурация в config/ или через переменные окружения, зависимости в requirements.txt или pyproject.toml, шаблоны Jinja2 в templates/. Стиль: форматирование Black, сортировка импортов isort, имена в snake_case и PascalCase, длина строки до 88 символов, абсолютные импорты. Отдельные разделы — аннотации типов, фабрика Flask и Blueprints, SQLAlchemy с миграциями Alembic, аутентификация через Flask-Login и bcrypt, REST на Flask-RESTful, тесты на pytest, безопасность и производительность.
Правило привязано к стеку: Flask, SQLAlchemy, Alembic, Flask-Login, Flask-RESTful, pytest. Если у вас FastAPI, Django или другой ORM, половина пунктов будет спорить с вашим кодом, и файл придётся переписать под себя. Это обычный markdown, так что правки вносятся руками.
Какие задачи решает
- задать раскладку src-layout и папку tests с первого коммита
- удержать Black, isort и лимит строки в 88 символов
- выбрать фабрику Flask и Blueprints вместо одного большого файла
- подключить SQLAlchemy с миграциями Alembic
- закрыть аутентификацию через Flask-Login и bcrypt
Примеры запросов агенту
- Создай структуру проекта: src-layout, tests рядом с src, конфиг в config/
- Разбей роуты Flask по Blueprints и вынеси модели в отдельные модули
- Настрой pytest с фикстурами и покрой тестами все роуты
Как установить python
Вручную: положить файлы
.cursor/rules/python.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/python.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/python.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/python.mdВручную: положить файлы
.clinerules/python.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Из того же набора68
Похожие
Рядом в теме «Языки программирования»
Все правила IDE по теме «Языки программирования» →Вопросы о python
Как установить правило python в Cursor?
Создайте файл .cursor/rules/python.mdc в корне проекта и вставьте в него содержимое правила. Cursor подхватит его по маске **/*.py, src/**/*.py, tests/**/*.py.
Что делает это правило?
Задаёт агенту договорённости по Python-проекту: структуру папок, форматирование Black и isort, аннотации типов, фабрику Flask с Blueprints, SQLAlchemy и Alembic, тесты на pytest.
Подойдёт ли оно для FastAPI или Django?
Нет, разделы про Flask, Flask-Login и Flask-RESTful рассчитаны на этот фреймворк. Для другого стека файл нужно переписать.
Исходный текст
python.mdc · CC0-1.0
--- description: "Python best practices and patterns for modern software development with Flask and SQLite" globs: **/*.py, src/**/*.py, tests/**/*.py alwaysApply: false --- # Python Best Practices ## Project Structure - Use src-layout with `src/your_package_name/` - Place tests in `tests/` directory parallel to `src/` - Keep configuration in `config/` or as environment variables - Store requirements in `requirements.txt` or `pyproject.toml` - Place static files in `static/` directory - Use `templates/` for Jinja2 templates ## Code Style - Follow Black code formatting - Use isort for import sorting - Follow PEP 8 naming conventions: - snake_case for functions and variables - PascalCase for classes - UPPER_CASE for constants - Maximum line length of 88 characters (Black default) - Use absolute imports over relative imports ## Type Hints - Use type hints for all function parameters and returns - Import types from `typing` module - Use `Optional[Type]` instead of `Type | None` - Use `TypeVar` for generic types - Define custom types in `types.py` - Use `Protocol` for duck typing ## Flask Structure - Use Flask factory pattern - Organize routes using Blueprints - Use Flask-SQLAlchemy for database - Implement proper error handlers - Use Flask-Login for authentication - Structure views with proper separation of concerns ## Database - Use SQLAlchemy ORM - Implement database migrations with Alembic - Use proper connection pooling - Define models in separate modules - Implement proper relationships - Use proper indexing strategies ## Authentication - Use Flask-Login for session management - Implement Google OAuth using Flask-OAuth - Hash passwords with bcrypt - Use proper session security - Implement CSRF protection - Use proper role-based access control ## API Design - Use Flask-RESTful for REST APIs - Implement proper request validation - Use proper HTTP status codes - Handle errors consistently - Use proper response formats - Implement proper rate limiting ## Testing - Use pytest for testing - Write tests for all routes - Use pytest-cov for coverage - Implement proper fixtures - Use proper mocking with pytest-mock - Test all error scenarios ## Security - Use HTTPS in production - Implement proper CORS - Sanitize all user inputs - Use proper session configuration - Implement proper logging - Follow OWASP guidelines ## Performance - Use proper caching with Flask-Caching - Implement database query optimization - Use proper connection pooling - Implement proper pagination - Use background tasks for heavy operations - Monitor application performance ## Error Handling - Create custom exception classes - Use proper try-except blocks - Implement proper logging - Return proper error responses - Handle edge cases properly - Use proper error messages ## Documentation - Use Google-style docstrings - Document all public APIs - Keep README.md updated - Use proper inline comments - Generate API documentation - Document environment setup ## Development Workflow - Use virtual environments (venv) - Implement pre-commit hooks - Use proper Git workflow - Follow semantic versioning - Use proper CI/CD practices - Implement proper logging ## Dependencies - Pin dependency versions - Use requirements.txt for production - Separate dev dependencies - Use proper package versions - Regularly update dependencies - Check for security vulnerabilities
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules