Cursor Rules Template: Flask SQLAlchemy Factory Pattern
Cursor Rules Template for Flask + SQLAlchemy using the Application Factory pattern. Includes a copyable .cursorrules block to guide Cursor AI in backend construction, testing, and security.
Target User
Backend developers building Flask apps with SQLAlchemy using the Application Factory pattern
Use Cases
- Establish a repeatable Flask + SQLAlchemy project structure using AppFactory
- Enforce a clean architecture with factories, repositories, and services
- Provide Cursor AI-guided development rules for secure, testable code
- Automate linting, testing, and deployment workflows
- Standardize ORM usage and migrations across teams
Markdown Template
Cursor Rules Template: Flask SQLAlchemy Factory Pattern
Overview
Direct answer: This Cursor rules configuration provides a Flask + SQLAlchemy backend workflow using the Application Factory pattern, with Cursor AI guidance that enforces stack-specific structure, security, and testability. It is tailored for Python web development with a modular, testable architecture.
The Cursor Rules Template covers Flask application bootstrapping, SQLAlchemy ORM usage, Blueprint-based routing, and an injection-friendly factory setup. It ensures code generation adheres to modern Python standards, includes a testable service layer, and preserves clear boundaries between models, factories, and routes.
When to Use These Cursor Rules
- Starting a new Flask project that uses SQLAlchemy as the ORM and the Application Factory pattern.
- Creating maintainable testable code with a clear separation of concerns (models, factories, services, routes).
- Enforcing consistent code style, dependencies, and directory layout across teams.
- Guiding Cursor AI to produce safe, production-ready patterns suitable for deployments and migrations.
Copyable .cursorrules Configuration
Paste this block into your project root as .cursorrules to drive Cursor AI for this Flask + SQLAlchemy factory pattern stack.
.cursorrules
Framework: Flask
Language: Python
Stack: Flask-SQLAlchemy-Factory
Context: You are a backend engineer building a Flask app that uses SQLAlchemy ORM with the Application Factory pattern. Produce maintainable, secure code and tests. Do not bypass ORM sessions or app context.
CodeStyle: Black, isort, Flake8; enforce PEP8
Architecture: AppFactory pattern, blueprints, service and repository layers
DirectoryRules: app/, app/models/, app/factories/, app/routes/, tests/
Authentication: JWT via Flask-JWT-Extended; avoid hard-coded secrets; store hashed passwords
Database: SQLAlchemy ORM; migrations with Alembic; use session scopes per request
Testing: pytest, pytest-flask; fixture-based database setup; deterministic seeds
Linting/CI: pre-commit hooks; GitHub Actions for tests and lint
Security: CSRF protection via Flask-WTF when forms; TLS in production; rotate keys regularly
ProhibitedActions: Do not import models across modules without explicit injection; Do not perform DB operations outside app/context; Do not hard-code secrets; Do not bypass migrations for schema changes
Recommended Project Structure
myapp/
app/
__init__.py
config.py
extensions.py
factories/
__init__.py
app_factory.py
models/
__init__.py
user.py
post.py
repositories/
__init__.py
user_repo.py
services/
__init__.py
user_service.py
routes/
__init__.py
user_routes.py
tests/
conftest.py
test_user.py
migrations/
Core Engineering Principles
- Explicit is better than implicit: clear factory boundaries and injection points.
- Separation of concerns: models, factories, routes, and services live in distinct modules.
- Testability: design for unit and integration tests with deterministic fixtures.
- Security-by-default: avoid exposing secrets, use secure defaults, CSRF protections, and proper auth flows.
- Maintainability: small, well-scoped components; minimize circular dependencies.
- Observability: meaningful logs, structured errors, and easy-to-test failure modes.
Code Construction Rules
- Use an AppFactory pattern: create_app(config_object) and register_blueprints().
- Configure SQLAlchemy via extension initialization in app context, not in module globals.
- Keep models simple and map to dedicated factories in app/factories/ for test data.
- Route handlers should interact with a service layer, which in turn uses repositories for data access.
- Use environment-based configuration for production vs. development settings and enable migrations.
- Follow PEP8; run Black and Flake8 before commits; keep imports ordered with isort.
- Avoid raw SQL in application code; rely on SQLAlchemy ORM and expressions.
- Do not access the database outside an application context or request scope.
Security and Production Rules
- Store secrets in environment variables; never check them into source control.
- Enable CSRF protection for forms; lose CSRF support only behind proper toggles in non-form endpoints.
- Use HTTPS in production; configure TLS certificates and secure cookies (HttpOnly, Secure).
- Set session lifetime and token expiration for JWTs; rotate credentials regularly.
- Validate and sanitize all inputs; rely on ORM parameter binding to prevent SQL injection.
- Gracefully handle database errors and mask internal details from clients.
Testing Checklist
- Unit tests for models and services with isolated in-memory database; verify factory-produced objects.
- Integration tests for routes with test client; verify auth flows and CRUD operations.
- Migration tests to ensure schema changes apply without data loss.
- Linting and type checks in CI; run pre-commit locally.
- Check security headers, CSRF, and configuration toggles in production-like settings.
Common Mistakes to Avoid
- Bypassing the AppFactory: importing and using a global Flask app instance.
- Mixing concerns in models and business logic; avoid tight coupling between controllers and data access.
- Ignoring migrations; changing schemas without Alembic results in drift.
- Storing plaintext secrets or credentials in code or environment traces.
- Not validating input or relying on client-side validation alone.
FAQ
What is the purpose of this Flask SQLAlchemy Cursor Rules Template?
The template provides a concrete, copyable set of Cursor AI rules for building Flask apps with SQLAlchemy using the Application Factory pattern. It ensures a consistent architecture, testability, and secure deployment practices suitable for Cursor AI-assisted development.
How does the AppFactory pattern integrate with Cursor Rules?
The rules enforce creating an app via create_app(config) and registering blueprints, extensions, and routers in a predictable order. This makes generated code easier to test, mock, and migrate, while keeping configuration isolated and injectable.
Where should I place the factories and repositories?
Place factories under app/factories to generate test data and domain-specific objects. Repositories live under app/repositories and are consumed by services. This separation aids testability and clean boundaries between data access and business logic.
Can I adapt these rules to other SQL backends or to asynchronous Flask setups?
Yes. The rules focus on structure, patterns, and security. For other backends or async contexts, adjust the ORM bindings and session management while preserving the AppFactory structure and Cursor AI constraints.
How do I run tests with an in-memory database?
Configure pytest fixtures to create an in-memory SQLite database per test, bind the session to the Flask app context, and tear down after each test. Ensure migrations and factory data are reset between tests.Overview
Direct answer: This Cursor rules configuration provides a Flask + SQLAlchemy backend workflow using the Application Factory pattern, with Cursor AI guidance that enforces stack-specific structure, security, and testability. It is tailored for Python web development with a modular, testable architecture.
The Cursor Rules Template covers Flask application bootstrapping, SQLAlchemy ORM usage, Blueprint-based routing, and an injection-friendly factory setup. It ensures code generation adheres to modern Python standards, includes a testable service layer, and preserves clear boundaries between models, factories, and routes.
When to Use These Cursor Rules
- Starting a new Flask project that uses SQLAlchemy as the ORM and the Application Factory pattern.
- Creating maintainable testable code with a clear separation of concerns (models, factories, services, routes).
- Enforcing consistent code style, dependencies, and directory layout across teams.
- Guiding Cursor AI to produce safe, production-ready patterns suitable for deployments and migrations.
Copyable .cursorrules Configuration
Paste this block into your project root as .cursorrules to drive Cursor AI for this Flask + SQLAlchemy factory pattern stack.
.cursorrules
Framework: Flask
Language: Python
Stack: Flask-SQLAlchemy-Factory
Context: You are a backend engineer building a Flask app that uses SQLAlchemy ORM with the Application Factory pattern. Produce maintainable, secure code and tests. Do not bypass ORM sessions or app context.
CodeStyle: Black, isort, Flake8; enforce PEP8
Architecture: AppFactory pattern, blueprints, service and repository layers
DirectoryRules: app/, app/models/, app/factories/, app/routes/, tests/
Authentication: JWT via Flask-JWT-Extended; avoid hard-coded secrets; store hashed passwords
Database: SQLAlchemy ORM; migrations with Alembic; use session scopes per request
Testing: pytest, pytest-flask; fixture-based database setup; deterministic seeds
Linting/CI: pre-commit hooks; GitHub Actions for tests and lint
Security: CSRF protection via Flask-WTF when forms; TLS in production; rotate keys regularly
ProhibitedActions: Do not import models across modules without explicit injection; Do not perform DB operations outside app/context; Do not hard-code secrets; Do not bypass migrations for schema changes
Recommended Project Structure
myapp/
app/
__init__.py
config.py
extensions.py
factories/
__init__.py
app_factory.py
models/
__init__.py
user.py
post.py
repositories/
__init__.py
user_repo.py
services/
__init__.py
user_service.py
routes/
__init__.py
user_routes.py
tests/
conftest.py
test_user.py
migrations/
Core Engineering Principles
- Explicit is better than implicit: clear factory boundaries and injection points.
- Separation of concerns: models, factories, routes, and services live in distinct modules.
- Testability: design for unit and integration tests with deterministic fixtures.
- Security-by-default: avoid exposing secrets, use secure defaults, CSRF protections, and proper auth flows.
- Maintainability: small, well-scoped components; minimize circular dependencies.
- Observability: meaningful logs, structured errors, and easy-to-test failure modes.
Code Construction Rules
- Use an AppFactory pattern: create_app(config_object) and register_blueprints().
- Configure SQLAlchemy via extension initialization in app context, not in module globals.
- Keep models simple and map to dedicated factories in app/factories/ for test data.
- Route handlers should interact with a service layer, which in turn uses repositories for data access.
- Use environment-based configuration for production vs. development settings and enable migrations.
- Follow PEP8; run Black and Flake8 before commits; keep imports ordered with isort.
- Avoid raw SQL in application code; rely on SQLAlchemy ORM and expressions.
- Do not access the database outside an application context or request scope.
Security and Production Rules
- Store secrets in environment variables; never check them into source control.
- Enable CSRF protection for forms; lose CSRF support only behind proper toggles in non-form endpoints.
- Use HTTPS in production; configure TLS certificates and secure cookies (HttpOnly, Secure).
- Set session lifetime and token expiration for JWTs; rotate credentials regularly.
- Validate and sanitize all inputs; rely on ORM parameter binding to prevent SQL injection.
- Gracefully handle database errors and mask internal details from clients.
Testing Checklist
- Unit tests for models and services with isolated in-memory database; verify factory-produced objects.
- Integration tests for routes with test client; verify auth flows and CRUD operations.
- Migration tests to ensure schema changes apply without data loss.
- Linting and type checks in CI; run pre-commit locally.
- Check security headers, CSRF, and configuration toggles in production-like settings.
Common Mistakes to Avoid
- Bypassing the AppFactory: importing and using a global Flask app instance.
- Mixing concerns in models and business logic; avoid tight coupling between controllers and data access.
- Ignoring migrations; changing schemas without Alembic results in drift.
- Storing plaintext secrets or credentials in code or environment traces.
- Not validating input or relying on client-side validation alone.
FAQ
What is the purpose of this Flask SQLAlchemy Cursor Rules Template?
The template provides a concrete, copyable set of Cursor AI rules for building Flask apps with SQLAlchemy using the Application Factory pattern. It ensures a consistent architecture, testability, and secure deployment practices suitable for Cursor AI-assisted development.
How does the AppFactory pattern integrate with Cursor Rules?
The rules enforce creating an app via create_app(config) and registering blueprints, extensions, and routers in a predictable order. This makes generated code easier to test, mock, and migrate, while keeping configuration isolated and injectable.
Where should I place the factories and repositories?
Place factories under app/factories to generate test data and domain-specific objects. Repositories live under app/repositories and are consumed by services. This separation aids testability and clean boundaries between data access and business logic.
Can I adapt these rules to other SQL backends or to asynchronous Flask setups?
Yes. The rules focus on structure, patterns, and security. For other backends or async contexts, adjust the ORM bindings and session management while preserving the AppFactory structure and Cursor AI constraints.
How do I run tests with an in-memory database?
Configure pytest fixtures to create an in-memory SQLite database per test, bind the session to the Flask app context, and tear down after each test. Ensure migrations and factory data are reset between tests.