duck.app.app¶
Attributes¶
Attribute |
Description |
|---|---|
|
The address and port for the Django server. |
|
The domain name for the application. |
|
Time to wait for the Django server to start. |
|
Indicates if the main application server is running. |
|
Indicates if the Django server is responsive. |
Methods¶
Application Control¶
run(): Starts the application and all services.stop(): Stops the application.restart(): Restarts the application.
Server Management¶
start_server(): Starts the main application server.start_django_server(): Starts Django and configures Duck as a reverse proxy.start_force_https_server(): Launches the HTTPS redirection service.
Background Services¶
start_ducksight_reloader(): Monitors file changes for live reloading.start_automations_dispatcher(): Handles scheduled automation scripts.
Event Handling & Security¶
register_signals(): Registers signal handlers for clean exits.on_app_start(): Event triggered when the application setup is complete.
Application Instance Management¶
The App class ensures that only one instance of the application is running at a time.
For microservices or smaller applications, use the MicroApp class instead.
Exceptions Handled¶
ApplicationError: Raised if multiple instances ofAppare created.SettingsError: Raised for misconfigurations in application settings.SSLError: Raised if SSL certificates or private keys are missing/invalid.
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(addr: str = 'localhost', port: int = 8000, domain: str = None, uses_ipv6: bool = False, no_checks: bool = False, disable_signal_handler: bool = False, disable_ipc_handler: bool = False, skip_setup: bool = False, enable_force_https_logs: bool = False, start_bg_eventloop_if_wsgi: bool = True, process_name: str = 'duck-server', workers: Optional[int] = None, force_https_workers: Optional[int] = None, force_worker_processes: bool = False, force_https_force_worker_processes: bool = False)¶
Initializes and configures the Duck application.
Initialization
Initializes the main Duck application instance.
This constructor sets up the application server, including optional Django integration, HTTPS redirection, and automation dispatching. It validates IP configuration, initializes environment settings, performs startup checks, and prepares runtime threads for the core services.
- Parameters:
addr – The IP address or hostname the server will bind to. Defaults to “localhost”.
port – The port number to run the application on. Defaults to 8000.
domain – The public-facing domain for the app. If not provided, defaults to
addr.uses_ipv6 – Whether to use IPv6 for networking. Defaults to False.
no_checks – If True, skips initial environment checks. Defaults to False.
disable_signal_handler – If True, disables setup of OS-level signal handlers. Defaults to False.
disable_ipc_handler – If True, disables setup of inter-process communication handlers. Defaults to False.
skip_setup – If True, skips setting up Duck environment, e.g. setting up urlpatterns and blueprints.
enable_force_https_logs – If True, force https microapp logs will be outputed to console. Defaults to False.
start_bg_eventloop_if_wsgi – If True, it starts a request handling event loop in background thread for offloading coroutines in
WSGIenvironment. This is useful for running asynchronous protocols likeHTTP/2andWebSocketseven inWSGIenvironment.process_name – The name of the process for this application. Defaults to “duck-server”.
workers – Number of workers to use. None will disable workers.
force_https_workers – Number of workers to use for HTTPS redirects. None will disable workers.
force_worker_processes –
Determines whether to use worker processes instead of the default worker threads. By default, when
workersis greater than 1, the server will use worker threads. Threads avoid cross-process synchronization issues—such as component registry mismatches (e.g., issues with Lively components) that occur when state lives in separate processes.Set this flag to
Trueonly when process isolation is explicitly desired and you do not require shared in-memory synchronization between workers.force_https_force_worker_processes – Whether to force use of multiple processes for
HTTPSredirect app. Defaults to False.
- Raises:
ApplicationError – If the provided address is invalid or if multiple main application
instances are created (only one is allowed). –
Side Effects:
Validates IP address format (IPv4 or IPv6).
Initializes HTTPS redirect server if
FORCE_HTTPSis enabled.Starts Django server if
USE_DJANGOis set.Starts the main application server.
Registers automation triggers if
RUN_AUTOMATIONSis enabled.Adds the application port to a port registry to prevent conflicts.
Notes:
Only a single instance of the main
Appshould be created. For additional services or sub-applications, useMicroApp.Set
disable_ipc_handler=Falseonly in a test environment. The IPC handler introduces a blocking mechanism that keeps the main interpreter running. Disabling it in production may lead to unhandled or improperly managed requests, as the blocking behavior is essential for proper execution. The app will be run in background andapp.runwon’t be blocking anymore.
- DJANGO_ADDR: tuple[str, int]¶
None
Specifies the host address and port for the Django server. For enhanced security, ensure that uncommon ports are used.
- DJANGO_SERVER_WAIT_TIME: int¶
None
Time in seconds to wait before checking if the Django server is up and running. This variable is used to periodically verify the server’s status during the initial startup or maintenance routines, ensuring that the server is ready to handle incoming requests.
- DOMAIN: str¶
None
Domain for the application used in building the application absolute URI.
- __instances__: int¶
0
The number of App instances, must be <= 1.
- __mainapp__¶
None
This is the main application instance.
- _run(print_ansi_art: bool = True)¶
Runs the Duck application.
- property absolute_uri: str¶
Returns application server absolute
URL.
- property absolute_ws_uri: str¶
Returns application server absolute WebSockets
URL.
- build_absolute_uri(path: str) str¶
Builds and returns absolute URL from provided path.
- build_absolute_ws_uri(path: str) str¶
Builds and returns absolute WebsSockets URL from provided path.
- static check_ssl_credentials()¶
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)
- property force_https_server_up: bool¶
Checks whether force HTTPS redirect micro application is running.
- Returns:
True if up else False
- Return type:
bool
- classmethod get_main_app() duck.app.app.App¶
Returns the main application instance if set.
- get_threadpool_futures() Dict[str, Optional[concurrent.futures.Future]]¶
Returns a dictionary of all application concurrent futures as a result of submitting tasks to the
ThreadPoolExector.Notes:
The
DuckSightReloadertask is run on an independent thread, so no future for it will be included in the dictionary.
- handle_ipc_messages()¶
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)¶
Method for handling process signals.
Signals:
SIGINT(Ctrl-C),SIGTERM(Terminate): Quits the server/application.
- classmethod instances() int¶
Returns number of Application instances.
- property meta: Dict[str, Any]¶
Get application metadata.
- on_app_start()¶
Event called when application has successfully been started.
- on_pre_stop()¶
Event called before final application termination.
- property process_id: int¶
Returns the application main process ID.
- record_metadata()¶
Sets or updates the metadata for the app, these changes will be globally available in
duck.meta.Metaclass.
- register_signals()¶
Register and bind signals to appropriate signal handler.
- run(print_ansi_art: bool = True)¶
Runs the Duck application.
- run_checks()¶
Runs application checks.
- property running: bool¶
Returns True if the main server running else False.
- property server_up: bool¶
Checks whether the main application server is up and running.
- Returns:
True if up else False
- Return type:
bool
- set_process_name()¶
Set the whole process name.
- start_automations_dispatcher(log_message: bool = True)¶
Starts automations dispatcher for executing automations during runtime.
- Parameters:
log_message – Whether to log something before starting the micro app.
Conditions:
RUN_AUTOMATIONS = True
- static start_background_workers(application: Union[duck.app.app.App, MicroApp], 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)¶
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_server()¶
Starts Django server and use Duck as reverse proxy server for Django.
- start_ducksight_reloader()¶
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
thread_pool_executor, this runs in an independant background thread withdaemon=True.
Conditions:
DEBUG = True
- start_force_https_server(log_message: bool = True)¶
Starts force HTTPS redirect micro application.
- Parameters:
log_message – Whether to log something before starting the micro app.
Conditions:
ENABLE_HTTPS = TrueFORCE_HTTPS = True
- start_server()¶
Starts the app server in new thread.
- stop(log_to_console: bool = True, no_exit: bool = False, call_on_pre_stop_handler: bool = True, kill_ducksight_reloader: bool = True, wait_for_thread_pool_executor_shutdown: bool = True, close_log_file: bool = True)¶
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.
call_on_pre_stop_handler – 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_thread_pool_executor_shutdown – Whether to wait for the thread pool executor to complete shutdown, meaning 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_force_https_server: bool = True, log_to_console: bool = True, wait: bool = True)¶
Stop all running servers i.e., Duck main server, Force HTTPS server & Django server.
- Parameters:
stop_force_https_server – Whether to stop Force HTTPS redirect microapp.
log_to_console – Whether to an exit message log to console.
wait – Whether to wait for termination. Defaults to True but with a timeout.