🔍 Code Extractor

function get_static_routes

Maturity: 46

Generates a list of Tornado URL route patterns for serving static files from specified directories, mapping URL slugs to filesystem paths.

File:
/tf/active/vicechatdev/patches/server.py
Lines:
553 - 571
Complexity:
simple

Purpose

This function is used in Tornado web applications to configure static file serving routes. It takes a dictionary mapping URL slugs to filesystem paths and returns properly formatted Tornado route patterns with StaticFileHandler. It includes validation to prevent using the reserved '/static' route and ensures all paths exist and are directories.

Source Code

def get_static_routes(static_dirs):
    """
    Returns a list of tornado routes of StaticFileHandlers given a
    dictionary of slugs and file paths to serve.
    """
    patterns = []
    for slug, path in static_dirs.items():
        if not slug.startswith('/'):
            slug = '/' + slug
        if slug == '/static':
            raise ValueError("Static file route may not use /static "
                             "this is reserved for internal use.")
        path = os.path.abspath(path)
        if not os.path.isdir(path):
            raise ValueError("Cannot serve non-existent path %s" % path)
        patterns.append(
            (r"%s/(.*)" % slug, StaticFileHandler, {"path": path})
        )
    return patterns

Parameters

Name Type Default Kind
static_dirs - - positional_or_keyword

Parameter Details

static_dirs: A dictionary where keys are URL slugs (strings) that will be used in the URL path, and values are filesystem paths (strings) pointing to directories containing static files to serve. Slugs will be automatically prefixed with '/' if not already present. The '/static' slug is reserved and will raise an error if used.

Return Value

Returns a list of tuples, where each tuple contains three elements: (1) a regex pattern string for URL matching in format 'r"/slug/(.*)"', (2) the StaticFileHandler class from Tornado, and (3) a dictionary with a 'path' key containing the absolute filesystem path. This list can be directly used to extend Tornado application URL patterns.

Dependencies

  • tornado
  • os

Required Imports

import os
from tornado.web import StaticFileHandler

Usage Example

import os
from tornado.web import StaticFileHandler, Application

def get_static_routes(static_dirs):
    patterns = []
    for slug, path in static_dirs.items():
        if not slug.startswith('/'):
            slug = '/' + slug
        if slug == '/static':
            raise ValueError("Static file route may not use /static this is reserved for internal use.")
        path = os.path.abspath(path)
        if not os.path.isdir(path):
            raise ValueError("Cannot serve non-existent path %s" % path)
        patterns.append(
            (r"%s/(.*)" % slug, StaticFileHandler, {"path": path})
        )
    return patterns

# Usage example
static_dirs = {
    'assets': '/var/www/assets',
    '/images': '/var/www/images',
    'css': './static/css'
}

routes = get_static_routes(static_dirs)
app = Application(routes)
# Routes will be: /assets/(.*), /images/(.*), /css/(.*)

Best Practices

  • Always ensure the directories specified in static_dirs exist before calling this function to avoid ValueError
  • Avoid using '/static' as a slug name as it is reserved for internal use
  • Use absolute paths or ensure relative paths are correctly resolved from the application's working directory
  • Validate that the application has appropriate read permissions for all directories being served
  • Consider security implications when serving static files - ensure sensitive files are not in served directories
  • The function automatically adds leading slashes to slugs, so both 'assets' and '/assets' are valid inputs
  • The returned patterns use regex capture groups '(.*)' to match any file path under the slug

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_static_handler 75.2% similar

    Creates a Tornado route handler tuple for serving static files in a Bokeh/Panel web application, with special handling for root path routing.

    From: /tf/active/vicechatdev/patches/server.py
  • function serve_generated_file 52.3% similar

    Flask route handler that serves generated files (images, HTML, CSS, JS, etc.) from session-specific directories, with security checks and automatic MIME type detection.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function serve_plot 48.6% similar

    Flask route handler that serves generated plot image files from a session-specific plots directory.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function download_file 45.7% similar

    Flask route handler that serves generated report files for download from a designated reports folder.

    From: /tf/active/vicechatdev/leexi/app.py
  • function smartstat_get_plot 45.3% similar

    Flask route handler that serves plot image files (PNG, JPG, SVG) generated by SmartStat analysis sessions from project directories.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse