CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-falcon

The ultra-reliable, fast ASGI+WSGI framework for building data plane APIs at scale.

Pending
Overview
Eval results
Files

application.mddocs/

Application Framework

Core WSGI and ASGI application classes that serve as the foundation for building Falcon web APIs. These classes handle request routing, middleware processing, and application-level configuration.

Capabilities

WSGI Application

The main WSGI application class that serves as the entry point for traditional synchronous web applications.

class App:
    def __init__(
        self,
        media_type: str = 'application/json',
        request_type: type = None,
        response_type: type = None,
        middleware: object = None,
        router: object = None,
        independent_middleware: bool = True,
        cors_enable: bool = False,
        sink_before_static_route: bool = True
    ):
        """
        Create a WSGI application.
        
        Args:
            media_type: Default media type for responses
            request_type: Custom Request class to use (default: falcon.Request)
            response_type: Custom Response class to use (default: falcon.Response)
            middleware: Single middleware component or iterable of components
            router: Custom router instance (default: CompiledRouter)
            independent_middleware: Process middleware independently
            cors_enable: Enable built-in CORS middleware
            sink_before_static_route: Process sinks before static routes
        """
    
    def __call__(self, env: dict, start_response: callable):
        """
        WSGI callable interface.
        
        Args:
            env: WSGI environment dictionary
            start_response: WSGI start_response callable
            
        Returns:
            Iterable of response body bytes
        """
    
    def add_route(self, uri_template: str, resource: object, **kwargs):
        """
        Add a route to the application.
        
        Args:
            uri_template: URI template with optional parameters (e.g., '/users/{user_id}')
            resource: Resource object with HTTP method handlers
            suffix: Optional route suffix for method-based routing
        """
    
    def add_static_route(self, prefix: str, directory: str, **kwargs):
        """
        Add a route for serving static files.
        
        Args:
            prefix: URI prefix for static files
            directory: Directory path containing static files
            downloadable: Set Content-Disposition header for downloads
            fallback_filename: Fallback file for missing resources
        """
    
    def add_sink(self, sink: callable, prefix: str = '/'):
        """
        Add a sink function to handle unmatched routes.
        
        Args:
            sink: Callable that accepts (req, resp) parameters
            prefix: URI prefix to match against
        """
    
    def add_middleware(self, middleware: object):
        """
        Add middleware component to the application.
        
        Args:
            middleware: Middleware object with process_request/process_response methods
        """
    
    def add_error_handler(self, exception_type: type, handler: callable):
        """
        Register custom error handler for specific exception types.
        
        Args:
            exception_type: Exception class to handle
            handler: Function that accepts (req, resp, ex, params)
        """
    
    def set_error_serializer(self, serializer: callable):
        """
        Set custom error serialization function.
        
        Args:
            serializer: Function that serializes HTTPError to response media
        """
    
    # Properties
    req_options: RequestOptions  # Request processing options (instance attribute)
    resp_options: ResponseOptions  # Response processing options (instance attribute)
    router_options: object  # Router configuration options

Usage Example

import falcon

class HealthCheckResource:
    def on_get(self, req, resp):
        resp.media = {'status': 'healthy'}

class UsersResource:
    def on_get(self, req, resp, user_id=None):
        if user_id:
            resp.media = {'user_id': user_id}
        else:
            resp.media = {'users': []}
    
    def on_post(self, req, resp):
        user_data = req.media
        # Process user creation
        resp.status = falcon.HTTP_201
        resp.media = {'created': True}

# Create application
app = falcon.App(
    cors_enable=True,
    media_type='application/json'
)

# Add routes
app.add_route('/health', HealthCheckResource())
app.add_route('/users', UsersResource())
app.add_route('/users/{user_id}', UsersResource())

# Add static file serving
app.add_static_route('/static', './public')

# Custom error handling
def handle_validation_error(req, resp, ex, params):
    resp.status = falcon.HTTP_400
    resp.media = {'error': 'Validation failed', 'details': str(ex)}

app.add_error_handler(ValueError, handle_validation_error)

ASGI Application

The ASGI application class for building modern asynchronous web applications with WebSocket support.

class falcon.asgi.App:
    def __init__(
        self,
        media_type: str = 'application/json',
        request_type: type = None,
        response_type: type = None,
        middleware: list = None,
        router: object = None,
        cors_enable: bool = False,
        req_options: RequestOptions = None,
        resp_options: ResponseOptions = None,
        secure_cookies_by_default: bool = None
    ):
        """
        Create an ASGI application.
        
        Args: Same as WSGI App constructor
        """
    
    async def __call__(self, scope: dict, receive: callable, send: callable):
        """
        ASGI callable interface.
        
        Args:
            scope: ASGI scope dictionary
            receive: ASGI receive callable  
            send: ASGI send callable
        """
    
    # Same methods as WSGI App:
    # add_route, add_static_route, add_sink, add_middleware, 
    # add_error_handler, set_error_serializer

ASGI Usage Example

import falcon.asgi

class AsyncUsersResource:
    async def on_get(self, req, resp, user_id=None):
        # Async database operation
        if user_id:
            user = await fetch_user(user_id)
            resp.media = user
        else:
            users = await fetch_all_users()
            resp.media = {'users': users}
    
    async def on_post(self, req, resp):
        user_data = req.media
        new_user = await create_user(user_data)
        resp.status = falcon.HTTP_201
        resp.media = new_user

class WebSocketResource:
    async def on_websocket(self, req, ws):
        await ws.accept()
        while True:
            try:
                message = await ws.receive_text()
                await ws.send_text(f"Echo: {message}")
            except falcon.WebSocketDisconnected:
                break

# Create ASGI application
app = falcon.asgi.App()

# Add routes
app.add_route('/users', AsyncUsersResource())
app.add_route('/users/{user_id}', AsyncUsersResource())
app.add_route('/ws', WebSocketResource())

Application Configuration Options

Configuration classes for customizing request and response processing behavior.

class RequestOptions:
    def __init__(
        self,
        auto_parse_form_urlencoded: bool = True,
        auto_parse_qs_csv: bool = True,  
        default_media_type: str = 'application/json',
        media_handlers: object = None,
        strip_url_path_trailing_slash: bool = True
    ):
        """
        Request processing configuration.
        
        Args:
            auto_parse_form_urlencoded: Auto-parse URL-encoded form data
            auto_parse_qs_csv: Parse comma-separated query parameters
            default_media_type: Default request media type
            media_handlers: Custom media handler registry
            strip_url_path_trailing_slash: Strip trailing slashes from paths
        """

class ResponseOptions:
    def __init__(
        self,
        default_media_type: str = 'application/json',
        media_handlers: object = None,
        secure_cookies_by_default: bool = None,
        static_media_types: dict = None
    ):
        """
        Response processing configuration.
        
        Args:
            default_media_type: Default response media type
            media_handlers: Custom media handler registry  
            secure_cookies_by_default: Set secure flag on cookies
            static_media_types: Media type mappings for static files
        """

Configuration Example

import falcon

# Create app first
app = falcon.App(cors_enable=True)

# Configure request/response options after creation
app.req_options.auto_parse_form_urlencoded = True
app.req_options.strip_url_path_trailing_slash = False

app.resp_options.secure_cookies_by_default = True
app.resp_options.default_media_type = 'application/json'

# Or create custom options and assign them
req_options = falcon.RequestOptions(
    auto_parse_form_urlencoded=True,
    strip_url_path_trailing_slash=False
)
app.req_options = req_options

Types

# Application types are the main App classes themselves
App: type  # WSGI application class
falcon.asgi.App: type  # ASGI application class

# Configuration option types
RequestOptions: type
ResponseOptions: type

Install with Tessl CLI

npx tessl i tessl/pypi-falcon

docs

application.md

asgi-websocket.md

error-handling.md

index.md

media.md

middleware-hooks.md

request-response.md

routing.md

testing.md

utilities.md

tile.json