Skip to content

Python uwsgi module stub

uwsgiconf comes with documented uwsgi module that you can import instead of import uwsgi.

1
2
3
4
5
# Instead of
import uwsgi

# you can do.
from uwsgiconf import uwsgi

That way uwsgi will be available runtime as usual, besides you will get autocompletion and hints in IDE, and won't get ImportError when run without uwsgi.

This also will facilitate your testing a bit, for those simple cases when you won't expect any result from uwsgi function.

Tip

This is a stub module, so it doesn't fully implement functions defined in it. Yet it tries to emulate uWSGI to some extent to facilitate testing. Use it for testing and documentation purposes.

uwsgi.is_stub

You can check runtime whether you're using a stub:

1
2
3
4
from uwsgiconf import uwsgi

if uwsgi.is_stub:
    ...

Forcing stub

Sometimes (e.g. for tests but when uWSGI module is available) you may want to force stub.

That could be done with the help of UWSGICONF_FORCE_STUB environment variable:

import os
os.environ['UWSGICONF_FORCE_STUB'] = '1'

Attributes

SPOOL_IGNORE

SPOOL_IGNORE: int = 0

Spooler function result.

Ignore this task, if multiple languages are loaded in the instance all of them will fight for managing the task. This return values allows you to skip a task in specific languages.


SPOOL_OK

SPOOL_OK: int = -2

Spooler function result.

The task has been completed, the spool file will be removed.


SPOOL_RETRY

SPOOL_RETRY: int = -1

Spooler function result.

Something is temporarily wrong, the task will be retried at the next spooler iteration.


SymbolsImporter

SymbolsImporter: type | None = None

SymbolsImporter type.


SymbolsZipImporter

SymbolsZipImporter: type | None = None

SymbolsZipImporter type.


ZipImporter

ZipImporter: type | None = None

ZipImporter type.


applications

applications: dict | None = None

Applications dictionary mapping mountpoints to application callables.

Note

Can be None.


buffer_size

buffer_size: int = 0

The current configured buffer size in bytes.


cores

cores: int = 0

Detected number of processor cores.


env

env: dict[str, str] = {}

Request environment dictionary.


has_threads

has_threads: bool = False

Flag indicating whether thread support is enabled.


hostname

hostname: bytes = b''

Current host name.


is_stub

is_stub: bool = True

Indicates whether stub is used instead of real uwsgi module.


magic_table

magic_table: dict = {}

Current mapping of configuration file "magic" variables.


mule_msg_hook

mule_msg_hook: Callable = lambda: None

Registers a function to be called for each mule message.


numproc

numproc: int = 0

Number of workers (processes) currently running.


opt

opt: dict[bytes, bytes] = {}

The current configuration options, including any custom placeholders.


post_fork_hook

post_fork_hook: Callable = lambda: None

Function to be called after process fork (spawning a new worker/mule).


sockets

sockets: list[int] = []

Current list of file descriptors for registered sockets.


spooler

spooler: Callable = lambda: None

Function to be called for spooler messages processing.


start_response

start_response: Callable | None = None

Callable spitting UWSGI response.


started_on

started_on: int = 0

uWSGI's startup Unix timestamp.


unbit

unbit: bool = False

Unbit internal flag.


version

version: bytes = b'0.0.0'

The uWSGI version string.


version_info

version_info: tuple[int, int, int, int, bytes] = (0, 0, 0, 0, b'')

Five-elements version number tuple.


Functions

accepting

accepting()

Called to notify the master that the worker is accepting requests, this is required for touch_chain_reload to work.


add_cron

1
2
3
4
5
6
7
8
add_cron(
    signal: int,  # (1)!
    minute: int,  # (2)!
    hour: int,  # (3)!
    day: int,  # (4)!
    month: int,  # (5)!
    weekday: int,  # (6)!
) -> bool
  1. Signal to raise.

  2. Minute 0-59. Defaults to each.

  3. Hour 0-23. Defaults to each.

  4. Day of the month number 1-31. Defaults to each.

  5. Month number 1-12. Defaults to each.

  6. Day of a the week number. Defaults to each. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday 4 - Thursday 5 - Friday 6 - Saturday

Adds cron. The interface to the uWSGI signal cron facility. The syntax is

Note

The last 5 arguments work similarly to a standard crontab, but instead of "*", use -1, and instead of "/2", "/3", etc. use -2 and -3, etc.

ValueError If unable to add cron rule.


add_file_monitor

1
2
3
4
add_file_monitor(
    signal: int,  # (1)!
    filename: str,  # (2)!
)
  1. Signal to raise.

  2. File or a directory to watch for its modification.

Maps a specific file/directory modification event to a signal.

ValueError If unable to register monitor.


add_ms_timer

1
2
3
4
add_ms_timer(
    signal: int,  # (1)!
    period: int,  # (2)!
)
  1. Signal to raise.

  2. The interval (milliseconds) at which to raise the signal.

Add a millisecond resolution timer.

ValueError If unable to add timer.


add_rb_timer

1
2
3
4
5
add_rb_timer(
    signal: int,  # (1)!
    period: int,  # (2)!
    repeat: int = 0,  # (3)!
)
  1. Signal to raise.

  2. The interval (seconds) at which the signal is raised.

  3. How many times to send signal. Will stop after the number is reached. Default: 0 - infinitely.

Add a red-black timer.

ValueError If unable to add timer.


add_timer

1
2
3
4
add_timer(
    signal: int,  # (1)!
    period: int,  # (2)!
)
  1. Signal to raise.

  2. The interval (seconds) at which to raise the signal.

Add timer.

ValueError If unable to add timer.


add_var

add_var(name: str, value: str) -> bool

Registers custom request variable.

Can be used for better integration with the internal routing subsystem.

ValueError If buffer size is not enough.


alarm

1
2
3
4
alarm(
    name: str, 
    message: str,  # (1)!
)
  1. Message to pass to alarm.

Issues the given alarm with the given message.

Note

to register an alarm use section.alarms.register_alarm(section.alarms.alarm_types.log('myalarm'))


async_connect

async_connect(socket: str) -> int

Issues socket connection. And returns a file descriptor or -1.


async_sleep

1
2
3
async_sleep(
    seconds: int,  # (1)!
) -> bytes
  1. Sleep time, in seconds.

Suspends handling the current request and passes control to the next async core.


cache_clear

1
2
3
cache_clear(
    cache: str,  # (1)!
)
  1. Cache name with optional address (if @-syntax is used).

Clears cache with the given name.


cache_dec

1
2
3
4
5
6
cache_dec(
    key: str, 
    value: int = 1, 
    expires: int | None = None,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. Expire timeout (seconds).

  2. Cache name with optional address (if @-syntax is used).

Decrements the specified key value by the specified value.


cache_del

1
2
3
4
cache_del(
    key: str,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. The cache key to delete.

  2. Cache name with optional address (if @-syntax is used).

Deletes the given cached key from the cache.


cache_div

1
2
3
4
5
6
cache_div(
    key: str, 
    value: int = 2, 
    expires: int | None = None,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. Expire timeout (seconds).

  2. Cache name with optional address (if @-syntax is used).

Divides the specified key value by the specified value.


cache_exists

1
2
3
4
cache_exists(
    key: str,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. The cache key to check.

  2. Cache name with optional address (if @-syntax is used).

Checks whether there is a value in the cache associated with the given key.


cache_get

1
2
3
4
cache_get(
    key: str,  # (1)!
    cache: str | None = None,  # (2)!
) -> bytes | None
  1. The cache key to get value for.

  2. Cache name with optional address (if @-syntax is used).

Gets a value from the cache.


cache_inc

1
2
3
4
5
6
cache_inc(
    key: str, 
    value: int = 1, 
    expires: int | None = None,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. Expire timeout (seconds).

  2. Cache name with optional address (if @-syntax is used).

Increments the specified key value by the specified value.


cache_keys

cache_keys(cache: str | None = None) -> list

Returns a list of keys available in cache.

ValueError If cache is unavailable.


cache_mul

1
2
3
4
5
6
cache_mul(
    key: str, 
    value: int = 2, 
    expires: int | None = None,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. Expire timeout (seconds).

  2. Cache name with optional address (if @-syntax is used).

Multiplies the specified key value by the specified value.


cache_num

1
2
3
4
cache_num(
    key: str,  # (1)!
    cache: str | None = None,  # (2)!
) -> int | None
  1. The cache key to get value for.

  2. Cache name with optional address (if @-syntax is used).

Gets the 64bit number from the specified item.


cache_set

1
2
3
4
5
6
cache_set(
    key: str, 
    value: bytes, 
    expires: int | None = None,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. Expire timeout (seconds).

  2. Cache name with optional address (if @-syntax is used).

Sets the specified key value.


cache_update

1
2
3
4
5
6
cache_update(
    key: str, 
    value: bytes, 
    expires: int | None = None,  # (1)!
    cache: str | None = None,  # (2)!
) -> bool
  1. Expire timeout (seconds).

  2. Cache name with optional address (if @-syntax is used).

Updates the specified key value.


call

1
2
3
4
call(
    func_name: bytes,  # (1)!
    *args: bytes
) -> bytes | None
  1. Function name to call with optional address (if @-syntax is used).

Performs an [RPC] function call with the given arguments.


chunked_read

1
2
3
chunked_read(
    timeout: int,  # (1)!
) -> bytes
  1. Wait timeout (seconds).

Reads chunked input.

IOError If unable to receive chunked part.


chunked_read_nb

chunked_read_nb() -> bytes

Reads chunked input without blocking.

IOError If unable to receive chunked part.


cl

cl() -> int

Returns current post content length.


close

1
2
3
close(
    fd: int,  # (1)!
)
  1. File descriptor.

Closes the given file descriptor.


connect

1
2
3
4
connect(
    socket: str,  # (1)!
    timeout: int = 0,  # (2)!
) -> int
  1. Socket name.

  2. Timeout (seconds).

Connects to the socket.


connection_fd

connection_fd() -> int

Returns current request file descriptor.


disconnect

disconnect()

Drops current connection.


embedded_data

1
2
3
embedded_data(
    symbol_name: str,  # (1)!
) -> bytes
  1. The symbol name to extract.

Reads a symbol from the uWSGI binary image.

ValueError If symbol is unavailable.


extract

extract(fname: str) -> bytes

Extracts file contents.


farm_get_msg

farm_get_msg() -> bytes | None

Reads a mule farm message.

ValueError If not in a mule


farm_msg

1
2
3
4
farm_msg(
    farm: str,  # (1)!
    message: str | bytes
)
  1. Farm name to send message to.

Sends a message to the given farm.


get_logvar

get_logvar(name: str) -> bytes

Return user-defined log variable contents.


green_schedule

green_schedule() -> bool

Switches to another green thread.

Note

Alias for suspend.


i_am_the_lord

i_am_the_lord(legion_name: str) -> bool

Returns flag indicating whether you are the lord of the given legion.


i_am_the_spooler

i_am_the_spooler() -> bool

Returns flag indicating whether you are the Spooler.


in_farm

1
2
3
in_farm(
    name: str,  # (1)!
) -> bool | None
  1. Farm name.

Returns flag indicating whether you (mule) belong to the given farm. Returns None is not in a mule.


is_a_reload

is_a_reload() -> bool

Returns flag indicating whether reloading mechanics is used.


is_connected

1
2
3
is_connected(
    fd: int,  # (1)!
) -> bool
  1. File descriptor

Checks the given file descriptor.


is_locked

1
2
3
is_locked(
    lock_num: int = 0,  # (1)!
) -> bool
  1. Lock number.

Checks for the given lock.

Note

Lock 0 is always available.

ValueError For Spooler or invalid lock number


listen_queue

1
2
3
listen_queue(
    socket_num: int = 0,  # (1)!
) -> int
  1. Socket number.

Returns listen queue (backlog size) of the given socket.

ValueError If socket is not found


lock

1
2
3
lock(
    lock_num: int = 0,  # (1)!
)
  1. Lock number.

Sets the given lock.

Note

Lock 0 is always available.

ValueError For Spooler or invalid lock number


log

log(message: str) -> bool

Logs a message.


log_this_request

log_this_request()

Instructs uWSGI to log current request data.


logsize

logsize() -> int

Returns current log size.


loop

loop() -> str | None

Returns current event loop name or None if loop is not set.


lord_scroll

lord_scroll(legion_name: str) -> bool

Returns a Lord scroll for the Legion.


masterpid

masterpid() -> int

Return the process identifier (PID) of the uWSGI master process.


mem

mem() -> tuple[int, int]

Returns memory usage tuple of ints: (rss, vsz).


metric_dec

metric_dec(key: str, value: int = 1) -> bool

Decrements the specified metric key value by the specified value.


metric_div

metric_div(key: str, value: int = 1) -> bool

Divides the specified metric key value by the specified value.


metric_get

metric_get(key: str) -> int

Returns metric value by key.


metric_inc

metric_inc(key: str, value: int = 1) -> bool

Increments the specified metric key value by the specified value.


metric_mul

metric_mul(key: str, value: int = 1) -> bool

Multiplies the specified metric key value by the specified value.


metric_set

metric_set(key: str, value: int) -> bool

Sets metric value.


metric_set_max

metric_set_max(key: str, value: int) -> bool

Sets metric value if it is greater that the current one.


metric_set_min

metric_set_min(key: str, value: int) -> bool

Sets metric value if it is less that the current one.


micros

micros() -> int

Returns uWSGI clock microseconds.


mule_get_msg

1
2
3
4
5
6
mule_get_msg(
    signals: bool | None = None,  # (1)!
    farms: bool | None = None,  # (2)!
    buffer_size: int = 65536, 
    timeout: int = -1,  # (3)!
) -> bytes
  1. Whether to manage signals.

  2. Whether to manage farms.

  3. Seconds.

Block until a mule message is received and return it.

This can be called from multiple threads in the same programmed mule.

ValueError If not in a mule.


mule_id

mule_id() -> int

Returns current mule ID. 0 if not a mule (e.g. worker).


mule_msg

1
2
3
4
mule_msg(
    message: str | bytes, 
    mule_farm: str | int | None = None,  # (1)!
) -> bool
  1. Mule ID, or farm name.

Sends a message to a mule(s)/farm.

ValueError If no mules, or mule ID or farm name is not recognized.


offload

offload(filename: str) -> bytes

Offloads a file.

Warning

Currently not implemented.

ValueError If unable to offload.


parsefile

parsefile(fpath: str)

Parses the given file.

Currently implemented only Spooler file parsing.


ready

ready() -> bool

Returns flag indicating whether we are ready to handle requests.


ready_fd

ready_fd() -> bool

Returns flag indicating whether file description related to request is ready.


recv

1
2
3
4
recv(
    fd: int, 
    maxsize: int = 4096,  # (1)!
) -> bytes
  1. Chunk size (bytes).

Reads data from the given file descriptor.


register_rpc

register_rpc(name: str, func: Callable) -> bool

Registers RPC function.

ValueError If unable to register function


register_signal

1
2
3
4
5
register_signal(
    number: int,  # (1)!
    target: str,  # (2)!
    func: Callable
)
  1. Signal number.

    • workers - run the signal handler on all the workers
    • workerN - run the signal handler only on worker N
    • worker/worker0 - run the signal handler on the first available worker
    • active-workers - run the signal handlers on all the active [non-cheaped] workers

    • mules - run the signal handler on all mules

    • muleN - run the signal handler on mule N
    • mule/mule0 - run the signal handler on the first available mule

    • spooler - run the signal on the first available spooler

    • farmN/farm_XXX - run the signal handler in the mule farm N or named XXX

    • http://uwsgi.readthedocs.io/en/latest/Signals.html#signals-targets

Registers a signal handler.

ValueError If unable to register


reload


request_id

request_id() -> int

Returns current request number (handled by worker on core).


route

1
2
3
4
route(
    name: str,  # (1)!
    args_str: str,  # (2)!
) -> int
  1. Route name

  2. Comma-separated arguments string.

Registers a named route for internal routing subsystem.


rpc

1
2
3
4
5
rpc(
    address: bytes | None, 
    func_name: bytes,  # (1)!
    *args: bytes
) -> bytes
  1. Function name to call.

Performs an RPC function call with the given arguments.

ValueError If unable to call RPC function.


rpc_list

rpc_list() -> tuple[bytes, ...]

Returns registered RPC functions names.


scrolls

scrolls(legion_name: str) -> list[str]

Returns a list of Legion scrolls defined on cluster.


send

send(fd_or_data: int | bytes, data: bytes | None = None) -> bool

Puts data into file descriptor.

  • One argument. Data to write into request file descriptor.
  • Two arguments. 1. File descriptor; 2. Data to write.

send_to_spooler

1
2
3
4
send_to_spooler(
    message: dict[bytes,  bytes] | None = None,  # (1)!
    **kwargs,  # (2)!
)
  1. The message to spool. Keys and values are bytes.

  2.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    Possible kwargs (these are also reserved `message` argument dictionary keys):
    
    * spooler: The spooler (id or directory) to use.
        Specify the ABSOLUTE path of the spooler that has to manage this task
    
    * priority: Number. The priority of the message. Larger - less important.
    
        .. warning:: This works only if you enable `order_tasks` option in `spooler.set_basic_params()`.
    
        This will be the subdirectory in the spooler directory in which the task will be placed,
        you can use that trick to give a good-enough prioritization to tasks.
    
        .. note:: This is for systems with few resources. For better approach use multiple spoolers.
    
    * at: Unix time at which the task must be executed.
        The task will not be run until the 'at' time is passed.
    
    * body: A binary body to add to the message,
        in addition to the message dictionary itself.
        Use this key for objects bigger than 64k, the blob will be appended
        to the serialized uwsgi packet and passed back t
        o the spooler function as the 'body' argument.
    

Send data to the The uWSGI Spooler. Also known as spool().

Warning

Either message argument should contain a dictionary this message dictionary will be constructed from kwargs.


sendfile

1
2
3
4
5
6
sendfile(
    fd_or_name: int | str,  # (1)!
    chunk_size: int = 0,  # (2)!
    start_pos: int = 0, 
    filesize: int = 0,  # (3)!
) -> bool | None
  1. File path or descriptor number.

  2. Not used.

  3. Filesize. If 0 will be determined automatically.

Runs a sendfile.


set_logvar

set_logvar(name: str, value: str)

Sets log variable.


set_spooler_frequency

set_spooler_frequency(seconds: int) -> bool

Sets how often the spooler runs.


set_user_harakiri

1
2
3
set_user_harakiri(
    timeout: int = 0,  # (1)!
)
  1. Seconds. 0 disable timer.

Sets user level harakiri.


set_warning_message

set_warning_message(message: str) -> bool

Sets a warning. This will be reported by pingers.


setprocname

setprocname(name: str)

Sets current process name.


signal

1
2
3
4
signal(
    num: int,  # (1)!
    remote: str = '',  # (2)!
)
  1. Signal number.

  2. Remote address.

Sends the signal to master or remote.

ValueError If remote rejected the signal.

IOError If unable to deliver to remote.


signal_received

signal_received() -> int

Get the number of the last signal received.

Used in conjunction with signal_wait.


signal_registered

signal_registered(num: int) -> int | None

Verifies the given signal has been registered.


signal_wait

signal_wait(num: int | None = None) -> str

Waits for the given of any signal.

Block the process/thread/async core until a signal is received. Use signal_received to get the number of the signal received. If a registered handler handles a signal, signal_wait will be interrupted and the actual handler will handle the signal.

SystemError If something went wrong.


spooler_get_task

1
2
3
spooler_get_task(
    path: str,  # (1)!
) -> dict | None
  1. The relative or absolute path to the task to read.

Returns a spooler task information.


spooler_jobs

spooler_jobs() -> list[str]

Returns a list of spooler jobs (filenames in spooler directory).


spooler_pid

spooler_pid() -> int

Returns first spooler process ID


spooler_pids

spooler_pids() -> list[int]

Returns a list of all spooler processes IDs.


stop

stop() -> bool | None

Stops uWSGI.


suspend

suspend() -> bool

Suspends handling of current coroutine/green thread and passes control to the next async core.


total_requests

total_requests() -> int

Returns the total number of requests managed so far by the pool of uWSGI workers.


unlock

1
2
3
unlock(
    lock_num: int = 0,  # (1)!
)
  1. Lock number.

Unlocks the given lock.

Note

Lock 0 is always available.

ValueError For Spooler or invalid lock number


wait_fd_read

1
2
3
4
wait_fd_read(
    fd: int,  # (1)!
    timeout: int | None = None,  # (2)!
) -> bytes
  1. File descriptor number.

  2. Timeout. Default: infinite.

Suspends handling of the current request until there is something to be read on file descriptor.

May be called several times before yielding/suspending to add more file descriptors to the set to be watched.

OSError If unable to read.


wait_fd_write

1
2
3
4
wait_fd_write(
    fd: int,  # (1)!
    timeout: int | None = None,  # (2)!
) -> bytes
  1. File descriptor number.

  2. Timeout. Default: infinite.

Suspends handling of the current request until there is nothing more to be written on file descriptor.

May be called several times to add more file descriptors to the set to be watched.

OSError If unable to read.


websocket_handshake

1
2
3
4
5
websocket_handshake(
    security_key: str | None = None,  # (1)!
    origin: str | None = None,  # (2)!
    proto: str | None = None,  # (3)!
)
  1. Websocket security key to use.

  2. Override Sec-WebSocket-Origin.

  3. Override Sec-WebSocket-Protocol.

Waits for websocket handshake.

IOError If unable to complete handshake.


websocket_recv

websocket_recv(request_context=None) -> bytes

Receives data from websocket.

IOError If unable to receive a message.


websocket_recv_nb

websocket_recv_nb(request_context=None) -> bytes

Receives data from websocket (non-blocking variant).

IOError If unable to receive a message.


websocket_send

1
2
3
4
websocket_send(
    message: str,  # (1)!
    request_context=None,  # (2)!
)
  1. data to send

  2. .. note:: uWSGI 2.1+

Sends a message to websocket.

IOError If unable to send a message.


websocket_send_binary

1
2
3
4
websocket_send_binary(
    message: str,  # (1)!
    request_context=None,  # (2)!
)
  1. data to send

  2. .. note:: uWSGI 2.1+

Sends binary message to websocket.

IOError If unable to send a message.


worker_id

worker_id() -> int

Returns current worker ID. 0 if not a worker (e.g. mule).


workers

workers() -> tuple[dict, ...]

Gets statistics for all the workers for the current server.

Returns tuple of dicts.