API Reference

Complete reference for all classes, functions, and constants in the Lcore framework.

Lcore

The main application class. Creates a WSGI-compatible application.

class Lcore (**kwargs)

Create a new Lcore application. Keyword arguments are added to app.config.

Routing Methods

MethodSignatureDescription
route(path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config)Register a route. Use as decorator or direct call.
get(path=None, **options)Shorthand for route(method='GET')
post(path=None, **options)Shorthand for route(method='POST')
put(path=None, **options)Shorthand for route(method='PUT')
delete(path=None, **options)Shorthand for route(method='DELETE')
patch(path=None, **options)Shorthand for route(method='PATCH')
error(code=500, callback=None)Register error handler for HTTP status code.
add_route(route)Add a Route object directly.
add_route_filter(name, pattern, to_python=None, to_url=None)Register a custom URL filter.

Mounting & Merging

MethodSignatureDescription
mount(prefix, app, **options)Mount a sub-app or WSGI app under a prefix.
merge(routes)Merge routes from another app.

Hook System

MethodSignatureDescription
add_hook(name, func)Register a hook callback.
remove_hook(name, func)Remove a hook callback.
trigger_hook(__name, *args, **kwargs)Trigger all callbacks for a hook. Returns list of results.
hook(name)Decorator to register a hook callback.
add_module_hook(prefix, hook_name, func)Register hook for mounted module prefix.
module_hook(prefix, hook_name)Decorator for module-specific hooks.
trigger_module_hooks(prefix, hook_name, *args, **kwargs)Trigger module hooks.

Plugin System

MethodSignatureDescription
install(plugin)Install a plugin. Calls setup(app).
uninstall(plugin)Uninstall by name or instance.
reset(route=None)Reset route cache. Re-applies plugins.

Middleware & DI

MethodSignatureDescription
use(middleware, routes=None, order=None)Register middleware.
inject(name, factory, lifetime='singleton')Register a dependency. Lifetimes: singleton, scoped, transient.

Utility Methods

MethodSignatureDescription
match(environ)Match a WSGI environ to a route.
get_url(routename, **kargs)Build URL from route name.
group(prefix, **common_config)Context manager for route grouping.
show_routes()List all routes as dicts.
show_middleware()List all middleware sorted by order.
api_docs()Generate API docs as dict.
api_docs_json()Generate API docs as JSON string.
run(**kwargs)Start server. Accepts server, host, port, debug, reloader.
close()Close app, trigger app_reset hooks.

Properties

PropertyTypeDescription
configConfigDictApplication configuration.
routeslist[Route]All registered routes.
routerRouterURL routing engine.
pluginslistInstalled plugins.
middlewareMiddlewarePipelineMiddleware pipeline.
resourcesResourceManagerFile resource manager.
catchallboolCatch all exceptions (from config).

BaseRequest

class BaseRequest (environ=None)

HTTP request wrapper around WSGI environ dict. Thread-local via request proxy.

Properties

PropertyTypeDescription
methodstrHTTP method (GET, POST, etc.)
pathstrRequest path
urlstrFull URL
fullpathstrPath with script_name
urlpartsSplitResultParsed URL components
query_stringstrRaw query string
script_namestrWSGI SCRIPT_NAME
content_typestrContent-Type header
content_lengthintContent-Length (-1 if invalid)
remote_addrstrClient IP address
remote_routelistIP chain from X-Forwarded-For
is_xhrboolXMLHttpRequest check
is_ajaxboolAlias for is_xhr
authtupleParsed Basic auth (user, pass) or None
chunkedboolChunked transfer encoding
headersWSGIHeaderDictRequest headers (case-insensitive)
cookiesFormsDictCookie values
query / GETFormsDictQuery string parameters
formsFormsDictForm body fields
paramsFormsDictCombined query + forms
filesFormsDictUploaded files (FileUpload objects)
jsondict/NoneParsed JSON body
bodyBytesIORaw request body stream
appLcoreParent application
routeRouteMatched route
url_argsdictURL parameter arguments

Methods

MethodSignatureDescription
get_header(name, default=None)Get a request header value.
get_cookie(key, default=None, secret=None, digestmod=sha256)Read cookie (with optional signature verification).
path_shift(shift=1)Shift path segments between script_name and path.
copy()Create a copy of this request.

BaseResponse

class BaseResponse (body='', status=None, headers=None, **more_headers)

HTTP response builder. Thread-local via response proxy.

Properties

PropertyTypeDescription
statusint/strHTTP status (read/write). Set with int or string.
status_codeintNumeric status code (read-only).
status_linestrFull status line like "200 OK" (read-only).
headersHeaderDictResponse headers.
headerlistlistHeaders as list of (name, value) tuples.
content_typestrContent-Type header.
content_lengthintContent-Length header.
expiresdatetimeExpires header.
charsetstrCharacter set from Content-Type.
bodystr/bytesResponse body.

Methods

MethodSignatureDescription
set_header(name, value)Set header (replaces existing).
add_header(name, value)Add header (allows duplicates).
get_header(name, default=None)Get response header.
set_cookie(name, value, secret=None, digestmod=sha256, **options)Set cookie. Options: max_age, expires, path, domain, secure, httponly, samesite.
delete_cookie(key, **kwargs)Delete cookie by setting max_age=-1.
copy(cls=None)Copy this response.
close()Close body if file-like.

RequestContext

class RequestContext (req=None, resp=None, app=None)

Per-request context object carrying state across middleware and handlers. Thread-local via ctx proxy.

AttributeTypeDescription
requestBaseRequestCurrent request.
responseBaseResponseCurrent response.
appLcoreApplication instance.
routeRouteMatched route.
request_idstrUnique request ID.
useranyUser info (set by auth).
statedictArbitrary per-request state.
MethodSignatureDescription
lazy(key, factory)Register a lazy-loaded attribute.

Router

class Router (strict=False)

URL routing engine. Matches URL paths to route targets.

MethodSignatureDescription
add(rule, method, target, name=None)Add a route rule.
match(environ)Match WSGI environ to a route. Returns (target, url_args).
build(_name, *anons, **query)Build URL from route name.
add_filter(name, func)Add custom filter function.

Route

class Route (app, rule, method, callback, name=None, plugins=None, skiplist=None, **config)

Represents a single route with metadata, plugins, and configuration.

Property/MethodTypeDescription
appLcoreParent application.
rulestrURL pattern.
methodstrHTTP method.
callbackcallableOriginal handler function.
namestrRoute name.
configConfigDictPer-route configuration.
callcallableCached callback (after plugin application).
reset()-Reset cached call.
prepare()-Pre-compute callback with plugins.
all_plugins()listGet all applicable plugins.
get_undecorated_callback()callableGet original callback.
get_callback_args()listGet callback parameter names.

ConfigDict

class ConfigDict ()

Configuration dictionary with metadata, overlays, and multi-source loading.

MethodSignatureDescription
load_module(name, squash=True)Load config from Python module.
load_config(filename, **options)Load from INI file.
load_dict(source, namespace='')Load from dict (flattens nested dicts).
load_env(prefix='LCORE_', strip_prefix=True)Load from environment variables.
load_json(filename)Load from JSON file.
load_dotenv(filename='.env')Load from .env file (validates key names).
validate_config(schema)Validate against dataclass schema.
update(*a, **ka)Update with optional prefix support.
setdefault(key, value=None)Set default value.
meta_get(key, metafield, default=None)Get metadata for a key.
meta_set(key, metafield, value)Set metadata for a key.

Middleware Classes

class Middleware

Base class. Attrs: name=None, order=50. Override __call__(self, ctx, next_handler).

class MiddlewareHook

Hook-based middleware. Override pre(ctx) and post(ctx, result).

class MiddlewarePipeline

Manages middleware chain. Methods: add(mw, routes, order), remove(mw), execute(ctx, handler).

Built-in Middleware

ClassConstructorOrder
ProxyFixMiddleware(trusted_proxies=None, num_proxies=1)-10 — run first
TimeoutMiddleware(timeout=30, max_workers=None)-5 — run early
Uses a persistent thread pool (not per-request). Returns 503 on deadline. Handler thread is not killed — it finishes in the background.
BodyLimitMiddleware(max_size=10*1024*1024)0
RequestIDMiddleware()1
RequestLoggerMiddleware(logger=None)2
CORSMiddleware(allow_origins='*', allow_methods=None, allow_headers=None, expose_headers=None, allow_credentials=False, max_age=86400)3
SecurityHeadersMiddleware(hsts=False, hsts_max_age=31536000, **overrides)5
CSRFMiddleware(secret=None, cookie_name='_csrf_token', header_name='X-CSRF-Token', safe_methods=('GET','HEAD','OPTIONS'))10 — cookie is httponly=False so JS/SPA clients can read and echo it as X-CSRF-Token; HMAC signing prevents cookie-tossing bypass
CompressionMiddleware(min_size=256, level=6, content_types=None)90

DependencyContainer

class DependencyContainer ()

Manages dependency injection with singleton, scoped, and transient lifetimes.

MethodSignatureDescription
register(name, factory, lifetime='singleton')Register a dependency factory.
resolve(name, ctx=None)Resolve dependency by name.
_begin_scope(ctx)Begin request scope.
_end_scope(ctx)End scope and close scoped deps.
__contains__(name)Check if dependency registered.
__len__()Count registered dependencies.

Exceptions

ExceptionParentDescription
HTTPResponseBaseResponseCan be raised to send immediate response. (body, status, headers)
HTTPErrorHTTPResponseError response with exception info. (status, body, exception, traceback)
LcoreExceptionExceptionBase framework exception.
RouteErrorLcoreExceptionRouting error base.
RouterUnknownModeErrorRouteErrorUnknown router mode.
RouteSyntaxErrorRouteErrorInvalid route pattern syntax.
RouteBuildErrorRouteErrorURL build failure.
PluginErrorLcoreExceptionPlugin conflict or error.
TemplateErrorLcoreExceptionTemplate loading/rendering error.
MultipartErrorHTTPErrorMultipart parsing error (400).

Data Structures

class MultiDict (*a, **k)

Dict supporting multiple values per key. Methods: get(key, default, index, type), append(key, value), replace(key, value), getall(key), allitems().

class FormsDict

Form data dict. Extends MultiDict. Methods: decode(encoding), getunicode(name, default, encoding). Supports attribute access.

class HeaderDict

Case-insensitive header dict. Extends MultiDict. Method: filter(names) to remove headers.

class WSGIHeaderDict (environ)

Read-only header dict wrapping WSGI environ. Method: raw(key, default) for raw environ value.

class FileUpload (fileobj, name, filename, headers=None)

Uploaded file wrapper. Props: filename (sanitized), content_type, content_length, file. Methods: save(dest, overwrite), get_header(name).

class ResourceManager (base='./', opener=open, cachemode='all')

File resource finder with caching. Methods: add_path(path, base, index, create), lookup(name), open(name, mode).

class AppStack

Stack of Lcore apps. Methods: push(value) / new_app(). Callable returns default app. Property: default.

class cached_property (func)

Thread-safe cached property descriptor with double-checked locking (RLock).

Utility Functions

FunctionSignatureDescription
tob(s, enc='utf8')Convert to bytes. None → b''.
touni(s, enc='utf8', err='strict')Convert to unicode string.
html_escape(string)Escape HTML special characters.
html_quote(string)Quote an HTML string.
makelist(data)Wrap in list if not already.
parse_auth(header)Parse HTTP Basic Auth header. Returns (user, pass).
parse_date(ims)Parse HTTP date string to timestamp.
parse_range_header(header, maxlen=0)Parse Range header. Returns list of (start, end).
http_date(value)Format datetime/timestamp as HTTP date string.
redirect(url, code=None)Raise a redirect HTTPResponse.
abort(code=500, text='Unknown Error.')Raise an HTTPError.
static_file(filename, root, mimetype=True, download=False, charset='UTF-8', etag=None, headers=None)Serve a static file with caching, range requests, and security.
load(target, **namespace)Dynamically load module/attribute (safe getattr chain).
load_app(target)Load WSGI app from "module:app" string.
debug(mode=True)Enable/disable debug mode globally.
run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, config=None, **kargs)Start a WSGI server.
pretty_error_page(exception, traceback_str=None)Generate styled HTML error page.

Security Utilities

FunctionSignatureDescription
hash_password(password, iterations=600000)Hash password using PBKDF2-SHA256 with random 32-byte salt. Returns 'pbkdf2:sha256:N$salt$hash'.
verify_password(password, hash_string)Verify password against PBKDF2 hash. Timing-safe via hmac.compare_digest.

Test Client

class TestClient (app)

WSGI test client. Calls app directly without HTTP — no server needed.

MethodSignatureDescription
request(method, path, body=b'', headers=None, query_string='', content_type=None, json=None)Send any HTTP method. Returns TestResponse.
get(path, **kw)GET request
post(path, **kw)POST request
put(path, **kw)PUT request
patch(path, **kw)PATCH request
delete(path, **kw)DELETE request
head(path, **kw)HEAD request
options(path, **kw)OPTIONS request
class TestResponse

Response object returned by TestClient methods.

PropertyTypeDescription
.statusstrFull status line: "200 OK"
.status_codeintHTTP status code: 200
.headersdictResponse headers
.bodybytesRaw response body
.textstrBody decoded as UTF-8
.jsondict/listBody parsed as JSON

BackgroundTaskPool

class BackgroundTaskPool (max_workers=4)

Thread-pool for fire-and-forget background tasks. Wraps concurrent.futures.ThreadPoolExecutor.

Method / PropertyDescription
.submit(fn, *args, **kwargs)Queue callable for background execution. Returns Future.
.pendingNumber of tasks still running or queued.
.shutdown(wait=True)Shut down pool. Blocks if wait=True.

Decorators

DecoratorSignatureDescription
@auth_basic(check, realm='private', text='Access denied')HTTP Basic authentication. check(user, pass) must return True.
@rate_limit(limit, per=60, max_buckets=10000, backend=None)Token bucket rate limiting per IP. In-process by default (each worker has independent buckets; effective limit per client = N × limit under N workers). Pass a RedisRateLimitBackend to enforce limits across all workers.
@validate_request(body=None, query=None)Validate request body/query against schema.
@on_shutdown(func)Register function to run on app shutdown.
@view(tpl_name, **defaults)Render SimpleTemplate when handler returns dict.
@jinja2_view(tpl_name, **defaults)Render Jinja2 template.
@mako_view(tpl_name, **defaults)Render Mako template.

Module-Level Wrappers

These wrap the default app's methods for convenience:

from lcore import route, get, post, put, delete, patch
from lcore import error, mount, hook, install, uninstall, url, use

Rate Limit Backends

class RateLimitBackend (abc.ABC)

Abstract base class for custom rate-limit storage. Subclass it and implement consume(key, limit, per) to plug any atomic store into @rate_limit(backend=...).

MethodSignatureDescription
consume(key, limit, per) -> boolAbstract. Atomically consume one token. Return True = allowed, False = blocked (429).
close()Optional. Release resources. Called on process exit if registered via @on_shutdown.
class RedisRateLimitBackend (redis_url='redis://localhost:6379/0', prefix='lcore:rl:', socket_connect_timeout=2, health_check_interval=30)

Built-in Redis-backed backend. Enforces per-IP limits across all worker processes via an atomic Lua script (INCR + EXPIRE in one round-trip). Requires: pip install redis.

Fails open (allows request, logs warning) when Redis is unavailable so a Redis outage cannot take down your application.

ParameterDefaultDescription
redis_url'redis://localhost:6379/0'Redis connection URL (redis://, rediss://, or unix://).
prefix'lcore:rl:'Key prefix used in Redis. Change it to namespace multiple apps.
socket_connect_timeout2Seconds before a connection attempt gives up.
health_check_interval30Seconds between background health-check pings to Redis.
from lcore import RedisRateLimitBackend, rate_limit

_rl = RedisRateLimitBackend('redis://localhost:6379/0')

@app.post('/api/login')
@rate_limit(5, per=300, backend=_rl)   # shared across all workers
def login(): ...

Template Classes

ClassEngineExtensions
BaseTemplateAbstract base.tpl .html .thtml .stpl
SimpleTemplateBuilt-inUses StplParser
Jinja2TemplateJinja2Requires jinja2
MakoTemplateMakoRequires mako
CheetahTemplateCheetahRequires cheetah3

All templates share: search(name, lookup), global_config(key), prepare(**options), render(*args, **kwargs).

Server Adapters

class ServerAdapter (host='127.0.0.1', port=8080, **options)

Base class for all server adapters. Override run(handler) to start the server.

AdapterServer NamePackage
WSGIRefServerwsgirefBuilt-in
CherootServercherootcheroot
WaitressServerwaitresswaitress
GunicornServergunicorngunicorn
GeventServergeventgevent
EventletServereventleteventlet
TornadoServertornadotornado
TwistedServertwistedtwisted
MeinheldServermeinheldmeinheld
BjoernServerbjoernbjoern
AiohttpServeraiohttpaiohttp
AiohttpUVLoopServeruvloopaiohttp + uvloop
PasteServerpastepaste
AutoServerautoAuto-detect

Module Constants

ConstantValueDescription
__version__'0.0.1'Framework version.
__author__'Lusan Sapkota'Author.
__license__'MIT'License.
TEMPLATE_PATH['./', './views/']Template search paths.
HTTP_CODESdictHTTP status code descriptions.
DEBUGFalseGlobal debug flag.
requestLocalRequestThread-local request proxy.
responseLocalResponseThread-local response proxy.
ctxLocalContextThread-local context proxy.
app / default_appAppStackDefault application stack.