duck.app.app¶
This module provides the core application class, App, for setting up and running a Duck-based web application. It supports various features, including:
HTTP/HTTPS Server: Configures and starts an HTTP or HTTPS server based on application settings.
Django Integration: Can forward requests to a Django server, supporting custom commands on startup.
SSL Management: Checks and manages SSL certificates for secure communication.
Force HTTPS: Redirects all HTTP traffic to HTTPS when enabled.
Automations: Supports running automation scripts during runtime.
Ducksight Reloader: Watches for file changes and enables dynamic reloading in DEBUG mode.
Port Management: Ensures that application ports are available.
Signal Handling: Gracefully handles termination signals (e.g.,
Ctrl+C) for clean shutdown.
Module Contents¶
Classes¶
Initializes and configures the Duck application. |
API¶
- class duck.app.app.App(name: Optional[str] = None, addr: str = DEFAULT_ADDR, port: int = DEFAULT_PORT, domain: Optional[str] = None, server_url: Optional[str] = None, uses_ipv6: bool = False, process_name: Optional[str] = None, workers: Optional[int] = None, force_worker_processes: bool = False, https_redirect_logs: bool = False, https_redirect_workers: Optional[int] = None, https_redirect_force_worker_processes: bool = False, start_bg_eventloop_if_wsgi: bool = True, disable_signal_handler: bool = False, disable_ipc_handler: bool = False, no_checks: bool = False, skip_setup: bool = False, events: Optional[Dict[str, Optional[Callable]]] = None)[source]¶
Bases:
duck.app.base.BaseAppInitializes and configures the Duck application.
Initialization
Initialize the main Duck application instance.
Sets up the application runtime, networking configuration, worker handling, HTTPS redirect support, and internal runtime services.
- Parameters:
name – Optional application name.
addr – Address or hostname to bind the server to.
port – Port to bind the server to.
domain – Public-facing domain name for the application. If not provided, the bound address is used.
server_url – Optional public-facing absolute server URL.
uses_ipv6 – Whether to use IPv6 networking.
process_name – Optional process name used for runtime identification.
no_checks – Whether to skip startup and environment checks.
skip_setup – Whether to skip automatic framework setup such as URL and blueprint registration.
disable_signal_handler – Whether to disable OS signal handlers.
disable_ipc_handler – Whether to disable the internal IPC handler.
start_bg_eventloop_if_wsgi – Whether to start a background asyncio event loop when running in a WSGI environment. This allows async protocols such as WebSockets and HTTP/2 to run under WSGI.
workers – Number of workers to use for the main application server.
Nonedisables workers.force_worker_processes –
Whether to use worker processes instead of threads for the main application server.
By default, Duck uses threads because they avoid cross-process synchronization issues involving shared in-memory state such as component registries.
Enable this only when process isolation is explicitly required.
https_redirect_logs – Whether to enable console logs for the HTTPS redirect server.
https_redirect_workers – Number of workers to use for the HTTPS redirect server.
Nonedisables workers.https_redirect_force_worker_processes – Whether to use worker processes instead of threads for the HTTPS redirect server.
events – Events to handle e.g. {“on_start”: some_callable}. Defaults to None.
- Raises:
ApplicationError – Raised if the provided address is invalid or if multiple main application instances are created.
… admonition:: Notes
Only one main
Appinstance should exist per process. UseMicroAppfor additional services or sub-applications.Disabling the IPC handler is intended mainly for testing. In normal environments, the IPC handler keeps the runtime alive and coordinated correctly.
- DEFAULT_ADDR¶
‘localhost’
- DEFAULT_PORT¶
8000
- __instances__¶
0
- __mainapp__¶
None
- _run(print_ansi_art: bool = True)[source]¶
Runs the Duck application.
Tunes the thread pool, starts background workers, launches the main server, and conditionally starts HTTPS redirect and Django servers. Calls the on_app_start handler once everything is verified as running.
- Parameters:
print_ansi_art – Whether to display the Duck ASCII art on startup.
- property absolute_uri: str¶
Returns application server absolute
URL- this is fetched usingduck.meta.Meta.
- property absolute_ws_uri: str¶
Returns application server absolute WebSockets
URL- this is fetched usingduck.meta.Meta.
- static check_ssl_credentials()[source]¶
This checks for ssl certfile and private key file existence.
- Raises:
SSLError – Either certfile or private key file is not found.
- property django_server_up: bool¶
Checks whether django server to forward requests to has started
- Returns:
True if up else False
- Return type:
started (bool)
- classmethod get_main_app() duck.app.app.App[source]¶
Returns the main application instance if set.
- get_runtime_futures() Dict[str, Optional[concurrent.futures.Future]][source]¶
Returns a dictionary of all application runtime concurrent futures.
Notes:
The
DuckSightReloadertask is run on an independent thread, so no future for it will be included.
- handle_ipc_messages()[source]¶
Handles incoming IPC messages from the shared file.
Notes:
This usually holds the main process from exiting because of the blocking behavior.
- handle_signal(sig, frame)[source]¶
Method for handling process signals.
Signals:
SIGINT(Ctrl-C),SIGTERM(Terminate): Quits the server/application.
- property https_redirect_server_up: bool¶
Checks whether HTTPS redirect micro application is running.
- Returns:
True if up else False
- Return type:
bool
- log_component_system_warnings()[source]¶
Warns about missing CSP flags required by the Lively component system.
Checks script-src for ‘unsafe-eval’ and style-src for ‘unsafe-inline’, logging warnings for any missing directives.
- log_startup_warnings()[source]¶
Logs configuration warnings before the server starts.
Covers allowed hosts, domain, and CSP policy checks relevant to the component system.
- property meta: Dict[str, Any]¶
Get global application metadata.
- property process_id: int¶
Returns the application main process ID.
- record_metadata()[source]¶
Sets or updates the metadata for the app, these changes will be globally available in
duck.meta.Metaclass.
- start_automations_dispatcher(log_message: bool = True)[source]¶
Starts automations dispatcher for executing automations during runtime.
- Parameters:
log_message – Whether to log something before starting the micro app.
- start_background_event_loop()[source]¶
Starts background threads and event loop(s) based on worker config.
With workers enabled, only the automations loop is started here — the rest are handled per-worker. Without workers, all managers are started directly, with the event loop conditional on ASYNC_HANDLING.
- static start_background_workers(application: duck.app.base.BaseApp, start_request_handling_threadpool_manager, start_request_handling_eventloop_manager, start_component_threadpool_manager: bool = True, start_automations_eventloop_manager: bool = False, recreate_managers: bool = False)[source]¶
Starts or restarts background workers, e.g.
AsyncioLoopManager&ThreadPoolManager.- Parameters:
application – The target application.
start_request_handling_threadpool_manager – Whether to start request handling threadpool in
WSGIenvironment. This is only valid in WSGI environment only.start_request_handling_eventloop_manager – Whether to start asyncio event loop either in
WSGIorASGIenvironment.start_component_threadpool_manager – Whether to start the background threadpool manager for HTML components rendering, assistance, etc. Defaults to True.
start_automations_eventloop_manager – Whether to start a dedicated event loop for running automations. Defaults to False.
recreate_managers – Whether to recreate managers for the current thread and all it’s descendents. Defaults to False. This argument doesn’t affect argument
start_automations_eventloop_manager. Argumentrecreate_managersonly applies to every other manager except the automations eventloop manager.
Notes:
This is usually useful when starting new worker processes/threads.
Use methods
get_or_create_loop_managerandget_or_create_thread_managerto create new managers before this function if new managers are needed.This only focus on default
AsyncioLoopManager&ThreadPoolManager.The thread manager is only run in
WSGImode but loop manager can be run in any environment (ASGI or WSGI).
- start_django_if_needed() bool[source]¶
Starts the Django server and waits for it to become responsive.
Runs any configured startup commands, then waits the configured grace period before checking Django’s health. Logs success details on a clean start or an error and stops the app on failure.
- Returns:
True if Django started successfully (or is not in use), False otherwise.
- start_django_server() None[source]¶
Starts Django server and use Duck as reverse proxy server for Django.
- start_ducksight_reloader()[source]¶
Starts the DuckSight Reloader for reloading app on file modifications, deletions, etc.
Notes:
Unlike other tasks like starting Duck server, HTTPS redirect server, etc which will be run by the app’s
runtime_executor, this runs in an independant background thread withdaemon=True.
- start_https_redirect_if_needed(start_failure_msg: str) bool[source]¶
Starts the HTTPS redirect server if configured.
- Parameters:
start_failure_msg – Fallback message used if the redirect server fails.
- Returns:
True if the redirect server started (or was not needed), False on failure.
- start_https_redirect_server(log_message: bool = True)[source]¶
Starts HTTPS redirect micro application in a new process.
- Parameters:
log_message – Whether to log something before starting the micro app.
- stop(log_to_console: bool = True, no_exit: bool = False, dispatch_pre_stop_event: bool = True, kill_ducksight_reloader: bool = True, wait_for_runtime_executor_shutdown: bool = True, close_log_file: bool = True)[source]¶
Stops the application and terminates the whole program.
- Parameters:
no_exit – Whether to terminate everything but keep the program running.
log_to_console – Whether to log an exit message.
dispatch_pre_stop_event – Whether to call method
on_pre_stop. Defaults to True.kill_ducksight_reloader – This attempts to kill the
DuckSightReloader. Useful ifno_exit=True,wait_for_runtime_executor_shutdown – Whether to wait for the runtime executor to complete shutdown. This mean waiting for current tasks to finish/cancel. This is only used if argument
no_exit=Trueelse it is automaticallyFalse.close_log_file – Whether to close the log file. Defaults to True.
- stop_servers(stop_https_redirect_server: bool = True, log_to_console: bool = True, wait: bool = True)[source]¶
Stop all running servers i.e., Duck main server, HTTPS redirect server & Django server.
- Parameters:
stop_https_redirect_server – Whether to stop HTTPS redirect microapp server.
log_to_console – Whether to an exit message log to console.
wait – Whether to wait for termination. Defaults to True but with a timeout.