pystalk documentation

pystalk is a simple Python module for interacting with the beanstalk task queueing daemon. It doesn’t provide much magic, but is suitable for building all sorts of functionality on top of.

This work is available under the terms of the ISC License.

Contents

Members

class pystalk.BeanstalkClient(host: str, port: int = 11300, socket_timeout: float | None = None, auto_decode: bool = False, connect_timeout: float | None = None)[source]

Simple wrapper around the Beanstalk API.

Parameters:
  • host (str) – Hostname or IP address to connect to

  • port (int) – Port to connect to

  • socket_timeout (float) – Timeout to set on the socket.

  • auto_decode (bool) – Attempt to decode job bodies as UTF-8 when reading them

  • connect_timeout (float) – Timeout to use when establishing a socket connection. Defaults to socket_timeout.

Doesn’t provide any fanciness for writing consumers or producers. Just lets you invoke methods to call beanstalk functions.

Warning

Setting socket timeout to a value lower than the value you pass to blocking functions like reserve_job() will cause errors!

bury_job(job_id, pri=65536)[source]

Mark the given job_id as buried. The job must have been previously reserved by this connection

Parameters:
  • job_id – Job to bury

  • pri (int) – Priority for the newly-buried job. If not passed, will keep its current priority

close()[source]

Close any open connection to the Beanstalk server.

This object is still safe to use after calling close() ; it will automatically reconnect and re-establish any open watches / uses.

It is a logic error to close the connection while you have a reserved job

delete_job(job_id)[source]

Delete the given job id. The job must have been previously reserved by this connection

classmethod from_uri(uri: str, socket_timeout: float | None = None, auto_decode: bool = False, connect_timeout: float | None = None) → BeanstalkClient[source]

Construct a synchronous Beanstalk Client from a URI.

The URI may be of the form beanstalk://host:port or beanstalkd://host:port

IPv6 literals must be wrapped in brackets as per RFC 2732.

ignore(tube)[source]

Remove the given tube from the watchlist.

Parameters:

tube – Name of tube to remove from the watchlist

If all tubes are ignore() d, beanstalk will auto-add “default” to the watchlist to prevent the list from being empty. See watch() for more unformation.

kick_job(job_id)[source]

Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to the READY state.

kick_jobs(num_jobs)[source]

Kick some number of jobs from the buried queue onto the ready queue.

Parameters:

num_jobs (int) – Number of jobs to kick

If not that many jobs are in the buried queue, it will kick as many as it can.

list_tubes()[source]

Return a list of tubes that this beanstalk instance knows about

Return type:

list of tubes

pause_tube(tube, delay=3600)[source]

Pause a tube for some number of seconds, preventing it from issuing jobs.

Parameters:

delay (int) – Time to pause for, in seconds

There is no way to permanently pause a tube; passing 0 for delay actually un-pauses the tube.

See also

unpause_tube()

peek_buried()[source]

Peek at the top job on the buried queue

peek_buried_iter()[source]

Peek at buried jobs in sequence

peek_delayed()[source]

Peek at the job job on the delayed queue

peek_delayed_iter()[source]

Peek at delayed jobs in sequence

peek_ready()[source]

Peek at the job job on the ready queue.

Return type:

Job

peek_ready_iter()[source]

Peek at ready jobs in sequence

ping() → bool[source]

Check whether a connection to the beanstalk server can be opened.

put_job(data: str | bytes, pri: int = 65536, delay: int = 0, ttr: int = 120)[source]

Insert a new job into whatever queue is currently USEd

Parameters:
  • data (Text (either str which will be encoded as utf-8, or bytes which are already utf-8) – Job body

  • pri (int) – Priority for the job

  • delay (int) – Delay in seconds before the job should be placed on the ready queue

  • ttr (int) – Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker

See also

put_job_into()

Put a job into a specific tube

using()

Insert a job using an external guard

put_job_into(tube_name: str, data: str | bytes, pri: int = 65536, delay: int = 0, ttr: int = 120)[source]

Insert a new job into a specific queue. Wrapper around put_job().

Parameters:
  • tube_name (str) – Tube name

  • data (Text (either str which will be encoded as utf-8, or bytes which are already utf-8) – Job body

  • pri (int) – Priority for the job

  • delay (int) – Delay in seconds before the job should be placed on the ready queue

  • ttr (int) – Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker

See also

put_job()

Put a job into whatever the current tube is

using()

Insert a job using an external guard

release_job(job_id, pri=65536, delay=0)[source]

Put a job back on the queue to be processed (indicating that you’ve aborted it)

You can only release a job which you have reserved using reserve_job() or reserve_iter().

Parameters:
  • job_id – Job ID to return

  • pri (int) – New priority (if not passed, will use old priority)

  • delay (int) – New delay for job (if not passed, will use 0)

reserve_iter()[source]

Reserve jobs as an iterator. Ends iteration when there are no more jobs immediately available

reserve_job(timeout=5)[source]

Reserve a job for this connection. Blocks for TIMEOUT secionds and raises TIMED_OUT if no job was available

Parameters:

timeout (int) – Time to wait for a job, in seconds.

stats()[source]

Return a dictionary with a bunch of instance-wide statistics

Return type:

dict

stats_job(job_id)[source]

Fetch statistics about a single job

Return type:

dict

stats_tube(tube_name)[source]

Fetch statistics about a single tube

Parameters:

tube_name – Tube to fetch stats about

Return type:

dict

unpause_tube(tube)[source]

Unpause a tube which was previously paused with pause_tube().

See also

pause_tube()

use(tube)[source]

Start producing jobs into the given tube.

Parameters:

tube – Name of the tube to USE

Subsequent calls to put_job() insert jobs into this tube.

using(tube)[source]

Context-manager to insert jobs into a specific tube

Parameters:

tube – Tube to insert to

Yields out an instance of BeanstalkInsertingProxy to insert items into that tube

See also

use()

Change the default tube

put_job()

Put a job into whatever the current tube is

put_job_into()

Put a job into a specific tube

watch(tube)[source]

Add the given tube to the watchlist.

Parameters:

tube – Name of the tube to add to the watchlist

Note: Initially, all connections are watching a tube named “default”. If you manually call watch(), we will un-watch the “default” tube. To keep it in your list, first call watch() with the other tubes, then call watch() with “default”.

property watchlist
class pystalk.ProductionPool(clients: List[BeanstalkClient], round_robin: bool = True, backoff_time: float = 10.0, initial_shuffle: bool = True)[source]

A pool for producing jobs into a list of beanstalk servers. When an error occurs, job insertion will be re-attempted on the next server in the pool.

Parameters:
  • clients – List of beanstalk client instances to use

  • round_robin – If true, every insertion will go to a different server in the pool. If false, the server will only be changed when an exception occurs.

  • backoff_time – Number of seconds after an error before a server will be reused

  • initial_shuffle – Randomly shuffle clients at initialization

All clients should have a socket timeout set or else some errors will not be detected.

NOTE: This will give you at-least-once deliverability (presuming at least one server is up), but can easily result in jobs being issued multiple times. Only use this functionality with idempotent jobs.

This method of pooling is only suitable for use when producing jobs. For consuming jobs from a cluster of beanstalkd servers, consider the pystalkworker project.

classmethod from_env(env_var: str = 'BEANSTALKD_URLS', socket_timeout: float | None = 3.0, connect_timeout: float | None = 1.0, backoff_time: float = 10.0, round_robin: bool = True, initial_shuffle: bool = True, auto_decode: bool = False, environ: Mapping[str, str] | None = None) → ProductionPool[source]

Construct a pool from beanstalkd URLs read from an environment variable.

Equivalent to calling pystalk.connect_beanstalk() with no urls argument; see that function for details.

Parameters:
  • env_var – Name of the environment variable holding comma-separated URLs

  • socket_timeout – Socket timeout to set on all constructed clients

  • connect_timeout – Connect timeout to set on all constructed clients

  • backoff_time – Number of seconds after an error before a server will be reused

  • round_robin – If true, every insertion will go to a different server in the pool

  • initial_shuffle – Randomly shuffle clients at initialization

  • auto_decode – Whether bodies should be bytes (False) or strings (True)

  • environ – Mapping to read environment variables from (defaults to os.environ)

classmethod from_uris(uris: List[str], socket_timeout: float | None = None, auto_decode: bool = False, round_robin: bool = True, backoff_time: float = 10.0, initial_shuffle: bool = True, connect_timeout: float | None = None)[source]

Construct a pool from a list of URIs. See pystalk.client.Client.from_uri for more information.

Parameters:
  • uris – A list of URIs

  • socket_timeout – Socket timeout to set on all constructed clients

  • auto_decode – Whether bodies should be bytes (False) or strings (True)

  • connect_timeout – Connect timeout to set on all constructed clients

put_job(data: str | bytes, pri: int = 65536, delay: int = 0, ttr: int = 120)[source]

Insert a new job into whatever queue is currently USEd

Parameters:
  • data (Text (either str which will be encoded as utf-8, or bytes which are already utf-8) – Job body

  • pri (int) – Priority for the job

  • delay (int) – Delay in seconds before the job should be placed on the ready queue

  • ttr (int) – Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker

See also

put_job_into()

Put a job into a specific tube

using()

Insert a job using an external guard

put_job_into(tube_name: str, data: str | bytes, pri: int = 65536, delay: int = 0, ttr: int = 120)[source]

Insert a new job into a specific queue. Wrapper around put_job().

Parameters:
  • tube_name (str) – Tube name

  • data (Text (either str which will be encoded as utf-8, or bytes which are already utf-8) – Job body

  • pri (int) – Priority for the job

  • delay (int) – Delay in seconds before the job should be placed on the ready queue

  • ttr (int) – Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker

See also

put_job()

Put a job into whatever the current tube is

using()

Insert a job using an external guard

use(tube: str)[source]

Start producing jobs into the given tube.

Parameters:

tube – Name of the tube to USE

Subsequent calls to put_job() insert jobs into this tube.

pystalk.connect_beanstalk_pool(urls: str | Iterable[str] | None = None, *, env_var: str = 'BEANSTALKD_URLS', socket_timeout: float | None = 3.0, connect_timeout: float | None = 1.0, backoff_time: float = 10.0, round_robin: bool = True, initial_shuffle: bool = True, auto_decode: bool = False, environ: Mapping[str, str] | None = None) → ProductionPool[source]

Build a ProductionPool for producing jobs. This is not a client.

Warning

Returns a ProductionPool, not a BeanstalkClient. The pool only implements put_job and put_job_into. It does not implement reserve_job, watch, stats, using, close, or ping. Do not swap this in for the connect_beanstalk() helpers in billing, payment, subscription-processor, or awstoken: those return a BeanstalkClient, and a silent swap fails at runtime.

connect_beanstalk() is the same function, kept as an alias so existing imports keep working. Prefer connect_beanstalk_pool().

If urls is None, the URLs are read from environ[env_var] (environ defaults to os.environ) as a comma-separated string. URLs are parsed with parse_beanstalk_urls(). Raises ValueError if the environment variable is missing or if no URLs remain after parsing. No network connections are made; constructing clients does not connect.

Parameters:
  • urls – A comma-separated string of URLs, an iterable of URL strings, or None to read from the environment

  • env_var – Name of the environment variable to read when urls is None

  • socket_timeout – Socket timeout to set on all constructed clients

  • connect_timeout – Connect timeout to set on all constructed clients

  • backoff_time – Number of seconds after an error before a server will be reused

  • round_robin – If true, every insertion will go to a different server in the pool

  • initial_shuffle – Randomly shuffle clients at initialization

  • auto_decode – Whether bodies should be bytes (False) or strings (True)

  • environ – Mapping to read environment variables from (defaults to os.environ)

Returns:

A ProductionPool for the given URLs

pystalk.connect_beanstalk(urls: str | Iterable[str] | None = None, *, env_var: str = 'BEANSTALKD_URLS', socket_timeout: float | None = 3.0, connect_timeout: float | None = 1.0, backoff_time: float = 10.0, round_robin: bool = True, initial_shuffle: bool = True, auto_decode: bool = False, environ: Mapping[str, str] | None = None) → ProductionPool

Build a ProductionPool for producing jobs. This is not a client.

Warning

Returns a ProductionPool, not a BeanstalkClient. The pool only implements put_job and put_job_into. It does not implement reserve_job, watch, stats, using, close, or ping. Do not swap this in for the connect_beanstalk() helpers in billing, payment, subscription-processor, or awstoken: those return a BeanstalkClient, and a silent swap fails at runtime.

connect_beanstalk() is the same function, kept as an alias so existing imports keep working. Prefer connect_beanstalk_pool().

If urls is None, the URLs are read from environ[env_var] (environ defaults to os.environ) as a comma-separated string. URLs are parsed with parse_beanstalk_urls(). Raises ValueError if the environment variable is missing or if no URLs remain after parsing. No network connections are made; constructing clients does not connect.

Parameters:
  • urls – A comma-separated string of URLs, an iterable of URL strings, or None to read from the environment

  • env_var – Name of the environment variable to read when urls is None

  • socket_timeout – Socket timeout to set on all constructed clients

  • connect_timeout – Connect timeout to set on all constructed clients

  • backoff_time – Number of seconds after an error before a server will be reused

  • round_robin – If true, every insertion will go to a different server in the pool

  • initial_shuffle – Randomly shuffle clients at initialization

  • auto_decode – Whether bodies should be bytes (False) or strings (True)

  • environ – Mapping to read environment variables from (defaults to os.environ)

Returns:

A ProductionPool for the given URLs

pystalk.parse_beanstalk_urls(urls: str | Iterable[str]) → List[str][source]

Parse beanstalkd URLs into a list of URIs suitable for ProductionPool.from_uris().

Accepts either a comma-separated string (e.g. the contents of a BEANSTALKD_URLS environment variable) or an iterable of strings. Each entry is stripped of surrounding whitespace and single/double quotes, empty entries are dropped, and entries without a scheme have beanstalk:// prepended (IPv6 literals such as [::1]:11300 are supported). Scheme validation is left to BeanstalkClient.from_uri().

Parameters:

urls – A comma-separated string of URLs, or an iterable of URL strings

Returns:

A list of beanstalk:///beanstalkd:// URIs

class pystalk.NoMoreClients(message: str | bytes = 'No clients can process requests at this time')[source]

Raised when no client in a ProductionPool can take the request.

Subclass of BeanstalkError, so except BeanstalkError also catches the all-hosts-down case. except NoMoreClients still works, including for callers that imported the name from pystalk.pool rather than pystalk. Catch NoMoreClients before BeanstalkError if the two cases need to be distinguished.

Raised with no arguments. str() is unchanged.

class pystalk.BeanstalkError(message: str | bytes)[source]
class pystalk.BeanstalkConnectionError(host, port, err)[source]

Raised when the underlying socket connection to beanstalkd fails.

Distinguishes connection-level failures (e.g. connection refused, timeout, DNS errors, broken pipe, or connection reset) from beanstalk protocol errors. Carries the host and port that were being connected to, and preserves the original socket error both on err and via exception chaining.

This is a subclass of BeanstalkError so that existing except BeanstalkError callers continue to catch connection failures.

class pystalk.client.Job(job_id, job_data)[source]

Structure holding a job returned from Beanstalk

Variables:
  • job_id – Opaque identifier for the job (to be passed to BeanstalkClient.release_job() or BeanstalkClient.stats_job()).

  • job_data – Blob of the data. str if BeanstalkClient.auto_decode is True; otherwise bytes

class pystalk.client.BeanstalkInsertingProxy(beanstalk_client: BeanstalkClient, tube: str)[source]

Proxy object yielded by BeanstalkClient.using()

put_job(data: str | bytes, pri: int = 65536, delay: int = 0, ttr: int = 120)[source]

Method to insert a job into the tube selected with BeanstalkClient.using().

Parameters:
  • data (Text (either str which will be encoded as utf-8, or bytes which are already utf-8) – Job body

  • pri (int) – Priority for the job

  • delay (int) – Delay in seconds before the job should be placed on the ready queue

  • ttr (int) – Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker

Indices and tables