Wrapper to pika for an easy to use RabbitMQ interface.
Project description
Snacks
Snacks is a wrapper around pika to provide a convenient interface for RabbitMQ.
Installation
Snacks is available on PyPI and can be installed with:
pip install snacks
Configuration
from snacks.rabbit import RabbitApp
# These are all the default values if none are provided.
rabbit = RabbitApp(
host='localhost',
port=5672,
default_exchange='',
virtual_host='/',
username='guest',
password='guest'
)
Consume From Queues
To decorate a function as a consumer for a queue use the consumer
decorator.
@rabbit.consumer('queue.name')
def listen(event: str) -> None:
print(f'Received request: {event}')
Consume From Generated Queues
To decorate a function as a consumer for a generated queue using given
routing keys use the listener
decorator.
@rabbit.listener('routing_key')
def listen(event: str) -> None:
print(f'Received request: {event}')
RPC
To make a decorated function a remote procedure add a return.
@rabbit.listener('routing_key')
def listen(event: str) -> str:
print(f'Received request: {event}')
return 'Remote response.'
Type Hint Based Deserialization
If the request body in a decorated function has type hints, snacks will
try to map the received data to that type. This has added support for
Dataclasses JSON or any
other class with a from_json
method.
@dataclass_json
@dataclass
class Event:
type: str
data: Any
@rabbit.listener('routing_key')
def user_event(event: Event) -> None:
print(f'Received {event.type} with data {event.data}')
Full Example
from snacks.rabbit import RabbitApp
# Setup
rabbit = RabbitApp(default_exchange='snacks')
queue = 'snacks'
key = 'snackey'
rabbit.exchange_declare(exchange_type='topic', durable=True)
rabbit.queue_declare(queue=queue, durable=True)
rabbit.queue_bind(queue=queue, routing_key=key)
@rabbit.consumer([queue])
def listen(event: str) -> str:
print(f'Received request: {event}')
return 'Rabbits and pikas are snacks.'
if __name__ == '__main__':
r = rabbit.publish_and_receive('To a python.', key, serialize=bytes.decode)
print(f'Received response: {r}')
Output:
Received request: To a python.
Received response: Rabbits and pikas are snacks.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file snacks-0.3.1.tar.gz
.
File metadata
- Download URL: snacks-0.3.1.tar.gz
- Upload date:
- Size: 8.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.4.2 requests/2.24.0 setuptools/51.0.0 requests-toolbelt/0.8.0 tqdm/4.48.2 CPython/3.8.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | c8f1d9f4ccc2100dc6ce0298543f1280ebdcb006f111f13a7950a04b60e5036b |
|
MD5 | 690102d5d09a405a8e5d9f3a9c1c6d28 |
|
BLAKE2b-256 | 25126ac485d9ce6850c224fbe51d0900fecff27551549c3aef05aff7cbe7ba42 |