Skip to main content
< All Topics
Print

Flask Application Development

name: flask-application-development

description: Flask web application development with application factory pattern, blueprints, background jobs, and AI service integration. Use when building Flask APIs, structuring modular Flask projects, adding background task scheduling, or integrating Anthropic/Tavily/RSS services.

Flask Application Development

Instructions

Build well-structured Flask applications following these patterns.

Application factory:

  • Define create_app(config_name=None) in app/__init__.py to construct the Flask instance
  • Register extensions, blueprints, and error handlers inside the factory
  • Return the configured app — this enables testing with different configurations and avoids circular imports

Blueprints:

  • Group related routes into blueprints: api_bp = Blueprint('api', __name__, url_prefix='/api')
  • Register blueprints in the factory: app.register_blueprint(api_bp)
  • Each blueprint gets its own module with routes, models, and helpers

Request handling:

  • JSON APIs: access request.json (parsed body), request.args (query params), request.form (form data)
  • Validate input early; return structured error responses with appropriate HTTP status codes
  • Use @app.errorhandler for consistent error formatting across the application

Templates:

  • Jinja2 for server-rendered HTML: render_template('index.html', data=data)
  • Use template inheritance ({% extends "base.html" %}) for consistent layouts
  • Keep logic out of templates — prepare data in view functions

Configuration:

  • app.config.from_object('config.ProductionConfig') for class-based config
  • app.config.from_envvar('APP_SETTINGS') to override from environment
  • Never commit secrets; load sensitive values from environment variables

Background jobs:

  • APScheduler for in-process scheduled tasks: scheduler.add_job(func, 'interval', minutes=30)
  • Initialize the scheduler inside the application factory; guard against double-start in reloader mode
  • For heavy workloads, offload to Celery or RQ instead of in-process scheduling

Integration patterns (Patriot Agent reference architecture):

  • Anthropic SDK: anthropic.Anthropic(api_key=key).messages.create() for AI-powered features
  • Tavily: TavilyClient(api_key=key).search(query) for web search integration
  • feedparser: feedparser.parse(url) for RSS/Atom feed ingestion
  • Pattern: Flask serves the API, APScheduler runs periodic data collection, Anthropic processes content, results stored and served via endpoints
Table of Contents