or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

blueprints.mdcli.mdconfiguration.mdcontext-globals.mdcore-application.mdhelpers.mdindex.mdjson-support.mdrequest-response.mdrouting.mdsessions.mdsignals.mdtemplates.mdtesting.md
tile.json

tessl/pypi-flask

A simple framework for building complex web applications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask@3.1.x

To install, run

npx @tessl/cli install tessl/pypi-flask@3.1.0

index.mddocs/

Flask

A lightweight WSGI web application framework designed to make getting started quick and easy, with the ability to scale up to complex applications. Flask offers suggestions but doesn't enforce any dependencies or project layout, giving developers the freedom to choose their tools and libraries, with many community extensions available for adding new functionality.

Package Information

  • Package Name: Flask
  • Package Type: pypi
  • Language: Python
  • Installation: pip install flask

Core Imports

from flask import Flask

Common imports for web development:

from flask import (
    Flask, request, session, g, redirect, url_for, 
    abort, render_template, flash, jsonify, make_response
)

Basic Usage

from flask import Flask, render_template, request, jsonify

# Create Flask application
app = Flask(__name__)
app.secret_key = 'your-secret-key'

# Simple route
@app.route('/')
def home():
    return 'Hello, Flask!'

# Route with parameters
@app.route('/user/<name>')
def user_profile(name):
    return f'User: {name}'

# Handle different HTTP methods
@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
    if request.method == 'POST':
        data = request.get_json()
        return jsonify({'status': 'created', 'data': data}), 201
    else:
        return jsonify({'message': 'Hello from API'})

# Template rendering
@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)

# Run the application
if __name__ == '__main__':
    app.run(debug=True)

Architecture

Flask follows the WSGI specification and provides a minimalist foundation that can be extended:

  • Application Object: Central registry for views, URL rules, template configuration
  • Request Context: Per-request data (request, session, g) available during request processing
  • Application Context: Application-level data available during request processing and CLI commands
  • Blueprints: Modular applications that can be registered with the main app
  • Extensions: Third-party packages that extend Flask functionality

Flask's design philosophy emphasizes simplicity and flexibility, allowing developers to choose their preferred tools for databases, authentication, form validation, and other common web development tasks.

Capabilities

Core Application

The Flask application class and core functionality for creating WSGI applications, handling routing, and managing the request-response cycle.

class Flask:
    def __init__(
        self,
        import_name: str,
        static_url_path: str | None = None,
        static_folder: str | os.PathLike[str] | None = "static",
        static_host: str | None = None,
        host_matching: bool = False,
        subdomain_matching: bool = False,
        template_folder: str | os.PathLike[str] | None = "templates",
        instance_path: str | None = None,
        instance_relative_config: bool = False,
        root_path: str | None = None,
    ): ...
    
    def run(
        self,
        host: str | None = None,
        port: int | None = None,
        debug: bool | None = None,
        load_dotenv: bool = True,
        **options: Any
    ) -> None: ...
    
    def test_client(self, use_cookies: bool = True, **kwargs) -> FlaskClient: ...

Core Application

Routing and URL Handling

URL routing, endpoint registration, and URL generation functionality for mapping URLs to view functions and generating URLs from endpoints.

def route(self, rule: str, **options) -> Callable: ...
def add_url_rule(
    self,
    rule: str,
    endpoint: str | None = None,
    view_func: Callable | None = None,
    provide_automatic_options: bool | None = None,
    **options: Any
) -> None: ...
def url_for(
    endpoint: str,
    *,
    _anchor: str | None = None,
    _method: str | None = None,
    _scheme: str | None = None,
    _external: bool | None = None,
    **values: Any,
) -> str: ...

Routing

Request and Response Handling

Request and response objects for handling HTTP data, along with utilities for creating responses and handling request data.

class Request:
    method: str
    url: str
    base_url: str
    url_root: str
    path: str
    query_string: bytes
    args: ImmutableMultiDict
    form: ImmutableMultiDict
    files: ImmutableMultiDict
    values: ImmutableMultiDict
    json: Any
    headers: EnvironHeaders
    cookies: ImmutableMultiDict
    
    def get_json(self, force: bool = False, silent: bool = False, cache: bool = True): ...

class Response:
    def __init__(
        self,
        response=None,
        status=None,
        headers=None,
        mimetype=None,
        content_type=None,
        direct_passthrough=False
    ): ...

Request Response

Templates and Rendering

Template rendering using Jinja2, including template loading, context processing, and streaming templates.

def render_template(template_name_or_list: str, **context) -> str: ...
def render_template_string(source: str, **context) -> str: ...
def stream_template(template_name_or_list: str, **context) -> Iterator[str]: ...
def stream_template_string(source: str, **context) -> Iterator[str]: ...

Templates

Application Context and Globals

Context management and global objects available during request processing, including application context, request context, and proxy objects.

def has_app_context() -> bool: ...
def has_request_context() -> bool: ...
def copy_current_request_context(f: Callable) -> Callable: ...
def after_this_request(f: Callable) -> Callable: ...

# Global proxy objects
current_app: LocalProxy
request: LocalProxy  
session: LocalProxy
g: LocalProxy

Context and Globals

Helpers and Utilities

Utility functions for common web development tasks including redirects, aborts, file sending, and message flashing.

def redirect(location: str, code: int = 302) -> Response: ...
def abort(code: int | Response, *args, **kwargs) -> NoReturn: ...
def flash(message: str, category: str = "message") -> None: ...
def get_flashed_messages(
    with_categories: bool = False,
    category_filter: list = []
) -> list: ...
def send_file(
    path_or_file: os.PathLike | str | IO[bytes],
    mimetype: str | None = None,
    as_attachment: bool = False,
    download_name: str | None = None,
    conditional: bool = True,
    etag: bool | str = True,
    last_modified: datetime | int | float | None = None,
    max_age: int | Callable[[str | None], int | None] | None = None
) -> Response: ...
def send_from_directory(directory: str, path: str, **kwargs) -> Response: ...

Helpers

JSON Support

JSON serialization and deserialization functionality with Flask-specific enhancements and response creation.

def jsonify(*args, **kwargs) -> Response: ...
def dumps(obj, **kwargs) -> str: ...
def loads(s: str | bytes, **kwargs): ...
def dump(obj, fp, **kwargs) -> None: ...
def load(fp, **kwargs): ...

JSON Support

Blueprints

Modular application components that allow organizing related functionality and can be registered with Flask applications.

class Blueprint:
    def __init__(
        self,
        name: str,
        import_name: str,
        static_folder: str | None = None,
        static_url_path: str | None = None,
        template_folder: str | None = None,
        url_prefix: str | None = None,
        subdomain: str | None = None,
        url_defaults: dict | None = None,
        root_path: str | None = None,
        cli_group: str | None = None,
    ): ...
    
    def route(self, rule: str, **options) -> Callable: ...

Blueprints

Configuration Management

Application configuration system for managing settings, loading configuration from various sources, and environment-based configuration.

class Config(dict):
    def from_envvar(self, variable_name: str, silent: bool = False) -> bool: ...
    def from_file(self, filename: str, load: Callable = None, silent: bool = False) -> bool: ...
    def from_object(self, obj) -> None: ...
    def from_prefixed_env(self, prefix: str = "FLASK", *, loads: Callable = None) -> bool: ...
    def get_namespace(self, namespace: str, lowercase: bool = True, trim_namespace: bool = True) -> dict: ...

Configuration

Session Management

Session handling for maintaining user state across requests, including secure cookie sessions and custom session interfaces.

class SessionInterface:
    def get_cookie_name(self, app: Flask) -> str: ...
    def get_cookie_domain(self, app: Flask) -> str | None: ...
    def should_set_cookie(self, app: Flask, session) -> bool: ...
    def open_session(self, app: Flask, request: Request): ...
    def save_session(self, app: Flask, session, response: Response) -> None: ...

class SecureCookieSessionInterface(SessionInterface): ...

Sessions

Testing Support

Testing utilities including test client for making requests and CLI runner for testing command-line interfaces.

class FlaskClient:
    def get(self, *args, **kwargs) -> TestResponse: ...
    def post(self, *args, **kwargs) -> TestResponse: ...
    def put(self, *args, **kwargs) -> TestResponse: ...
    def delete(self, *args, **kwargs) -> TestResponse: ...
    def patch(self, *args, **kwargs) -> TestResponse: ...
    def head(self, *args, **kwargs) -> TestResponse: ...
    def options(self, *args, **kwargs) -> TestResponse: ...
    def trace(self, *args, **kwargs) -> TestResponse: ...

class FlaskCliRunner:
    def invoke(self, cli, args=None, input=None, env=None, **extra): ...

Testing

Signals

Event system for hooking into Flask's request processing lifecycle and application events.

# Signal objects (instances of blinker.base.NamedSignal)
template_rendered: NamedSignal
before_render_template: NamedSignal
request_started: NamedSignal
request_finished: NamedSignal
request_tearing_down: NamedSignal
got_request_exception: NamedSignal
appcontext_tearing_down: NamedSignal
appcontext_pushed: NamedSignal
appcontext_popped: NamedSignal
message_flashed: NamedSignal

Signals

Command Line Interface

CLI system for creating custom commands and managing Flask applications from the command line.

def with_appcontext(f: Callable) -> Callable: ...
def load_dotenv(path: str | None = None) -> bool: ...

class FlaskGroup(click.Group): ...
class AppGroup(click.Group): ...

CLI

Types

from typing import Any, Callable, Iterator, Union, IO
import os
from datetime import datetime
from werkzeug.wrappers import Response as BaseResponse
from werkzeug.datastructures import ImmutableMultiDict, EnvironHeaders
from werkzeug.local import LocalProxy

# Type aliases for return values
ResponseReturnValue = Union[
    Response,
    BaseResponse, 
    str,
    bytes,
    list,
    dict,
    tuple,
    Iterator
]

StatusCode = Union[int, str]
HeadersValue = Union[dict, list, tuple]