Skip to main content

Overview

The Flask application object is the central component of any Flask application. It acts as a registry for view functions, URL rules, template configuration, and much more.

Creating an Application

The most basic Flask application is created by instantiating the Flask class:
from flask import Flask

app = Flask(__name__)

The Import Name Parameter

The __name__ parameter is crucial as it helps Flask:
  • Locate resources (templates, static files)
  • Provide better debugging information
  • Help extensions determine the application’s location
For single-module applications, always use __name__. For packages, you can hardcode the package name:
app = Flask('yourapplication')
# or
app = Flask(__name__.split('.')[0])

Application Configuration

Flask provides a rich set of configuration options through the config attribute:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['DEBUG'] = True

Default Configuration

Flask comes with sensible defaults (from app.py:206-238):
{
    "DEBUG": None,
    "TESTING": False,
    "SECRET_KEY": None,
    "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
    "SESSION_COOKIE_NAME": "session",
    "SESSION_COOKIE_HTTPONLY": True,
    "MAX_CONTENT_LENGTH": None,
    "PREFERRED_URL_SCHEME": "http",
    # ... more options
}

Application Structure

Static Files

By default, Flask serves static files from a static folder:
app = Flask(__name__, 
            static_folder='static',
            static_url_path='/static')
Flask automatically creates a route at /static/<path:filename> to serve these files.

Templates

Templates are served from the templates folder by default:
app = Flask(__name__,
            template_folder='templates')

Running the Application

Development Server

For development, use the built-in server:
if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=5000)
The development server is not suitable for production. Use a production WSGI server like Gunicorn or uWSGI instead.

Command Line Interface

Flask also provides CLI commands:
flask run
flask run --debug
flask run --host=0.0.0.0 --port=8000

Application Methods

Resource Management

Open files relative to the application root:
with app.open_resource('schema.sql') as f:
    conn.executescript(f.read())
For instance-specific files:
with app.open_instance_resource('config.json') as f:
    config = json.load(f)

Test Client

Create a test client for testing:
def test_app():
    app.testing = True
    client = app.test_client()
    
    with client:
        rv = client.get('/?vodka=42')
        assert request.args['vodka'] == '42'

Application Lifecycle

First Request

Flask tracks whether the first request has been handled via the _got_first_request flag (from app.py:999-1010).

Request Processing Flow

  1. Request Started - Signal sent
  2. Before Request - Run preprocessing functions
  3. Dispatch Request - Match URL and call view function
  4. After Request - Process response
  5. Teardown - Clean up resources
@app.before_request
def before_request():
    # Runs before each request
    g.user = load_user()

@app.after_request
def after_request(response):
    # Runs after each request
    response.headers['X-Custom'] = 'value'
    return response

@app.teardown_request
def teardown_request(exception):
    # Always runs, even if exception occurred
    db.close()

Custom Application Classes

You can subclass Flask to customize behavior:
from flask import Flask

class CustomFlask(Flask):
    def create_jinja_environment(self):
        env = super().create_jinja_environment()
        env.filters['custom_filter'] = my_filter
        return env

app = CustomFlask(__name__)

Application Factory Pattern

For larger applications, use the application factory pattern:
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # Initialize extensions
    db.init_app(app)
    mail.init_app(app)
    
    # Register blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    
    return app

Best Practices

Use Application Factory

Create apps with factory functions for better testing and multiple instances

Configuration Management

Keep sensitive config in environment variables, not in code

Error Handling

Always register error handlers for production applications

Logging

Use app.logger for consistent logging across your application

Build docs developers (and LLMs) love