---
description: This rule explains Flask conventions and best practices for lightweight Python web applications.
globs: **/*.py
alwaysApply: false
---
# Flask rules
- Use Blueprints to organize routes by feature or resource
- Use Flask-SQLAlchemy for database models and ORM
- Use application factories for flexible application initialization
- Use Flask extensions for common functionality (Flask-Login, Flask-WTF, etc.)
- Store configuration in environment variables
- Use Flask-Migrate for database migrations
- Implement proper error handling with error handlers
- Use Flask-RESTful or similar for building APIs
This rule provides guidance on Flask conventions and best practices for building lightweight Python web applications. It offers recommendations for structuring your Flask projects, utilizing extensions, and implementing key functionality to ensure your web applications follow industry standards.
The Flask rule serves as a reference guide for developers working with Flask, a popular Python web framework. It outlines recommended practices for organizing your Flask applications, managing databases, handling authentication, and building APIs. By following these conventions, you can create more maintainable, scalable, and robust web applications.
Blueprints are a powerful feature in Flask that allow you to organize related routes and functionality into separate modules. The rule recommends using blueprints to group routes by feature or resource, which improves code organization and maintainability.
For example, you might structure your application with blueprints like this:
# auth/routes.py
from flask import Blueprint
auth_bp = Blueprint('auth', __name__)
@auth_bp.route('/login')
def login():
return "Login page"
# In your app factory
def create_app():
app = Flask(__name__)
from myapp.auth.routes import auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
return app
The rule emphasizes using Flask-SQLAlchemy for database operations and Flask-Migrate for managing database schema changes. This combination provides a powerful ORM and straightforward migration capabilities:
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy()
migrate = Migrate()
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
db.init_app(app)
migrate.init_app(app, db)
return app
Using application factories provides flexibility in initializing your Flask application, which is particularly useful for testing and different deployment environments:
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
# Initialize extensions
db.init_app(app)
login.init_app(app)
# Register blueprints
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
Implementing proper error handlers helps provide better user experience when things go wrong:
@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('500.html'), 500
The Flask rule (flask.mdc
) is automatically applied when you're working with Python files in your project, as indicated by its glob pattern of **/*.py
. This means that whenever you're editing a Python file and interact with Cursor's AI features (like Cmd+K or the AI chat), the assistant will have this Flask knowledge available.
You'll benefit from this rule when:
If you need to manually invoke the rule in a non-Python file, you can type @flask
in the chat or Cmd+K dialog to explicitly bring this context to the AI assistant.
As recommended by the rule, store your configuration in environment variables rather than hardcoding them:
# config.py
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-key'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///app.db'
MAIL_SERVER = os.environ.get('MAIL_SERVER')
# other config variables
For RESTful API development, use Flask-RESTful or similar extensions as suggested by the rule:
from flask_restful import Resource, Api
api = Api(app)
class UserResource(Resource):
def get(self, user_id):
user = User.query.get_or_404(user_id)
return user.to_dict()
def put(self, user_id):
# Update user
pass
api.add_resource(UserResource, '/api/users/<int:user_id>')
By following these conventions and best practices outlined in the Flask rule, you'll create more maintainable and robust Flask applications while getting the most out of Cursor's AI assistance for your Flask development work.