Cursor Rules for
Flask

This rule explains Flask conventions and best practices for lightweight Python web applications.
Back to rules
Type
Backend
Language(s)
Python
Stats
437 views
46 copies
19 downloads
flask.mdc
---
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.

What this rule does

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.

Key Flask best practices

Blueprint organization

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

Database management

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

Application factories

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

Error handling

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

Using Flask in Cursor

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:

  1. Asking for help structuring a new Flask application
  2. Requesting guidance on implementing Flask-specific features
  3. Seeking advice on Flask best practices
  4. Getting code suggestions that align with Flask conventions

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.

Practical tips for Flask development

Configuration management

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

API development

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.

Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later