function get_static_routes
Generates a list of Tornado URL route patterns for serving static files from specified directories, mapping URL slugs to filesystem paths.
/tf/active/vicechatdev/patches/server.py
553 - 571
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
tornadoos
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_static_handler 75.2% similar
-
function serve_generated_file 52.3% similar
-
function serve_plot 48.6% similar
-
function download_file 45.7% similar
-
function smartstat_get_plot 45.3% similar