Skip to main content

Lightweight, efficient and developer-friendly framework for mqtt communication.

Project description

FastCC Logo

FastCC

Ruff Mypy Gitmoji

FastCC is a Python package that simplifies MQTT communication using decorators. With its intuitive @route system, developers can quickly define MQTT message handlers without boilerplate code. FastCC natively supports Protocol Buffers :boom:, automatically handling serialization to byte format for efficient and structured data exchange.

  • Lightweight :zap:
  • Efficient :rocket:
  • Developer-friendly :technologist:

This project is built on top of aiomqtt which itself is built on top of paho-mqtt.

Examples

client.py

import asyncio
import contextlib
import logging
import os
import sys

import fastcc

_logger = logging.getLogger(__name__)


async def main() -> None:
    """Run the app."""
    logging.basicConfig(level=logging.DEBUG)

    async with fastcc.Client("localhost") as client:
        try:
            response = await client.request(
                "greet/doe",
                "Charlie",
                response_type=str,
            )
        except fastcc.RequestError as e:
            details = f"An error occurred on the server: {e}"
            _logger.error(details)

        response = await client.request("greet/doe", "Alice", response_type=str)
        _logger.info("response: %r", response)


loop_factory: type[asyncio.AbstractEventLoop] | None = None

# See: https://github.com/empicano/aiomqtt#note-for-windows-users
if sys.platform.lower() == "win32" or os.name.lower() == "nt":
    loop_factory = asyncio.SelectorEventLoop

with contextlib.suppress(KeyboardInterrupt):
    asyncio.run(main(), loop_factory=loop_factory)

app.py

import asyncio
import contextlib
import logging
import os
import sys

import fastcc

router = fastcc.Router()


@router.route("greet/{family}")
async def greet(packet: str, family: str, *, database: dict[str, int]) -> str:
    """Greet a user.

    Parameters
    ----------
    packet
        The name of the user.
        Autofilled by fastcc.
    family
        The family of the user.
        Autofilled by fastcc.
    database
        The database.
        Autofilled by fastcc.

    Returns
    -------
    str
        The greeting message.
    """
    # ... do some async work
    await asyncio.sleep(0.1)

    database[packet] += 1
    occurrence = database[packet]
    return (
        f"Hello, {packet} from the {family} family! Saw you {occurrence} times!"
    )


async def main() -> None:
    """Run the app."""
    logging.basicConfig(level=logging.DEBUG)

    database: dict[str, int] = {"Alice": 0, "Bob": 0}

    async with fastcc.Application("localhost") as app:
        app.add_router(router)
        app.add_injector(database=database)
        app.add_exception_handler(
            KeyError,
            lambda e: fastcc.RequestError(repr(e), fastcc.Status.NOT_FOUND),
        )
        await app.run()


loop_factory: type[asyncio.AbstractEventLoop] | None = None

# See: https://github.com/empicano/aiomqtt#note-for-windows-users
if sys.platform.lower() == "win32" or os.name.lower() == "nt":
    loop_factory = asyncio.SelectorEventLoop

with contextlib.suppress(KeyboardInterrupt):
    asyncio.run(main(), loop_factory=loop_factory)

stream_client.py

import asyncio
import contextlib
import logging
import os
import sys

import fastcc

_logger = logging.getLogger(__name__)


async def main() -> None:
    """Run the app."""
    logging.basicConfig(level=logging.DEBUG)

    async with fastcc.Client("localhost") as client:
        try:
            async for response in client.stream(
                "greet",
                "Charlie",
                response_type=str,
            ):
                _logger.info("response: %r", response)
        except fastcc.RequestError as e:
            details = f"An error occurred on the server: {e}"
            _logger.error(details)

        async for response in client.stream(
            "greet",
            "Alice",
            response_type=str,
        ):
            _logger.info("response: %r", response)


loop_factory: type[asyncio.AbstractEventLoop] | None = None

# See: https://github.com/empicano/aiomqtt#note-for-windows-users
if sys.platform.lower() == "win32" or os.name.lower() == "nt":
    loop_factory = asyncio.SelectorEventLoop

with contextlib.suppress(KeyboardInterrupt):
    asyncio.run(main(), loop_factory=loop_factory)

stream_app.py

import asyncio
import contextlib
import logging
import os
import sys
from collections.abc import AsyncIterator  # noqa: TC003

import fastcc

router = fastcc.Router()


@router.route("greet")
async def greet(
    packet: str,
    *,
    database: dict[str, int],
) -> AsyncIterator[str]:
    """Greet a user.

    Parameters
    ----------
    packet
        The name of the user.
        Autofilled by fastcc.
    database
        The database.
        Autofilled by fastcc.

    Yields
    ------
    str
        The greeting message.
    """
    # ... do some async work
    await asyncio.sleep(0.1)

    for _ in range(2):
        database[packet] += 1
        occurrence = database[packet]
        yield f"Hello, {packet}! Saw you {occurrence} times!"


async def main() -> None:
    """Run the app."""
    logging.basicConfig(level=logging.DEBUG)

    database: dict[str, int] = {"Alice": 0, "Bob": 0}
    async with fastcc.Application("localhost") as app:
        app.add_router(router)
        app.add_injector(database=database)
        app.add_exception_handler(
            KeyError,
            lambda e: fastcc.RequestError(repr(e), fastcc.Status.NOT_FOUND),
        )

        await app.run()


loop_factory: type[asyncio.AbstractEventLoop] | None = None

# See: https://github.com/empicano/aiomqtt#note-for-windows-users
if sys.platform.lower() == "win32" or os.name.lower() == "nt":
    loop_factory = asyncio.SelectorEventLoop

with contextlib.suppress(KeyboardInterrupt):
    asyncio.run(main(), loop_factory=loop_factory)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastcc-5.2.0.tar.gz (19.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastcc-5.2.0-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

Details for the file fastcc-5.2.0.tar.gz.

File metadata

  • Download URL: fastcc-5.2.0.tar.gz
  • Upload date:
  • Size: 19.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for fastcc-5.2.0.tar.gz
Algorithm Hash digest
SHA256 c8b594c0706ae7818a4208a9216fbc7b87d593343324eda29dd62d6b762dfec7
MD5 063e11040d08c101e18c468c4676be24
BLAKE2b-256 88235d035e96f1b5288fbd8a105408756f8cd861803521f56051d097c4197449

See more details on using hashes here.

File details

Details for the file fastcc-5.2.0-py3-none-any.whl.

File metadata

  • Download URL: fastcc-5.2.0-py3-none-any.whl
  • Upload date:
  • Size: 20.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for fastcc-5.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 11117e860588159f7dce8573e386c7ab6a2b439d9d573e1068f29e222e11e659
MD5 4059e599c789edb3029b7064334b285a
BLAKE2b-256 88e1998d0216b7c1a42d5687576d44954b1ed4d0cc8d785d0d5576d5f52896c5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page