Skip to main content

RabbitMQ Broker

Python versions Docker version Black code style Isort imports coverage

Не зависящий от фреймворков пакет для общения между микросервисами. Пакет предоставляет интерфейс для работы с брокером сообщений RabbitMQ и базовый класс цепочки обработчиков.

Пакет реализует паттерн цепочка обязанностей в синхронном и асинхронном виде.

Конфигурация

Переменная окружения Описание Значение по умолчанию
MICROSERVICE_SETTINGS Путь к модулю настроек проекта отно- "settings"
-сительно корня проекта. (Разделение
через точку: module1.module2.settings)

Использование

Цепочка обработчиков

Для использования цепочки обязанностей нужно импортировать базовый класс звена и унаследоваться от него. Необходимо установить параметр request_type. Обязательно должен быть переопределен абстрактный метод BaseChain.get_response_body(self, data):

from rmq_broker.chains.base import BaseChain


class LoginChain(BaseChain):
    request_type = "login"

    def get_response_body(self, data: dict) -> dict:
        ...

Также, можно унаследоваться от асинхронного варианта реализации:

from rmq_broker.async_chains.base import BaseChain


class LoginChain(BaseChain):
    request_type = "login"

    async def get_response_body(self, data: dict) -> dict:
        ...

Метод должен содержать логику обработки запроса и вызывать родительский метод BaseChain.form_response(data, body, code, message)

class LoginChain(BaseChain):
    request_type = "login"

    async def get_response_body(self, data):
        # Обработка запроса
        ...
        return super().form_response(data, response, status.HTTP_200_OK, "OK")

data: Изначальное сообщение. body: Обработанное тело запроса. code: HTTP код ответа. message: Сообщение к ответу.

Модели

Доработанные pydantic модели - могут быть использованы как для валидации, так и для генерации сообщения.

Валидация сообщения происходит так же, как и в обычной pydantic модели:

ProcessedMessage(**message_dict)

Для генерации сообщения необходимо создать объект модели, не передавая аргументы при инициализации, и вызвать метод generate. В аргументы метода generate можно передавать любой из ключей структуры сообщения, в том числе code, message, dst и src. Вложенная структура(header, status) формируется сама:

>>> ProcessedMessage().generate(dst="destination", code=201, request_type="creation")
>>> {"header": {"src": "", "dst": "destination"}, "request_type": "creation"...}

RPC брокер

Запуск прослушки и автоматического ответа на сообщения. В файле consumer.py:

from app.chains import your_chain
from rmq_broker.queues.rabbitmq import AsyncRabbitMessageQueue

async def broker_runner():
    async with AsyncRabbitMessageQueue() as provider:
        await provider.register_tasks("rpc_queue_name", your_chain.handle)
        await provider.consume()


asyncio.run(broker_runner())

Далее:

python3 consumer.py

Metadata

Release files for rabbitmq-broker 1.2.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rabbitmq-broker 1.2.6
File Size Uploaded Provenance Actions
rabbitmq_broker-1.2.6.tar.gz 15.9 kB Without provenance Details for rabbitmq_broker-1.2.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rabbitmq-broker 1.2.6
File Interpreter ABI Platform Actions
rabbitmq_broker-1.2.6-py3-none-any.whl Python 3 none any Details for rabbitmq_broker-1.2.6-py3-none-any.whl

Total release size: 38.2 kB

Release files / rabbitmq_broker-1.2.6.tar.gz

Download URL rabbitmq_broker-1.2.6.tar.gz
Size 15.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a861126db0633b3a7db9871db91d93428ce83816251fabe2ee3785226fe5f023
BLAKE2b-256 checksum
How to use checksums
dfa6f48bd9dc88a500fed86cb1ef434030d29ecd01bf82d94560dcd06c1317ca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.2

Release files / rabbitmq_broker-1.2.6-py3-none-any.whl

Download URL rabbitmq_broker-1.2.6-py3-none-any.whl
Size 22.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
08fbe50d1f75ac32e5997e5bf4c574e65d5dd242eb8bcabbec86372670b215d3
BLAKE2b-256 checksum
How to use checksums
0f4f322fd7f4a1141a2f96e8f3fd7089b618e34909cfa7944a28bd9ae8bdb5ac
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.2

Security for rabbitmq-broker 1.2.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page