faststream


Namefaststream JSON
Version 0.5.3 PyPI version JSON
download
home_pageNone
SummaryFastStream: the simplest way to work with a messaging queues
upload_time2024-04-23 12:16:41
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords framework kafka message brokers nats rabbitmq redis
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastStream

<b>Effortless event stream integration for your services</b>

---

<p align="center">
  <a href="https://github.com/airtai/faststream/actions/workflows/test.yaml" target="_blank">
    <img src="https://github.com/airtai/faststream/actions/workflows/test.yaml/badge.svg?branch=main" alt="Test Passing"/>
  </a>

  <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/airtai/faststream" target="_blank">
      <img src="https://coverage-badge.samuelcolvin.workers.dev/airtai/faststream.svg" alt="Coverage">
  </a>

  <a href="https://www.pepy.tech/projects/faststream" target="_blank">
    <img src="https://static.pepy.tech/personalized-badge/faststream?period=month&units=international_system&left_color=grey&right_color=green&left_text=downloads/month" alt="Downloads"/>
  </a>

  <a href="https://pypi.org/project/faststream" target="_blank">
    <img src="https://img.shields.io/pypi/v/faststream?label=PyPI" alt="Package version">
  </a>

  <a href="https://pypi.org/project/faststream" target="_blank">
    <img src="https://img.shields.io/pypi/pyversions/faststream.svg" alt="Supported Python versions">
  </a>

  <br/>

  <a href="https://github.com/airtai/faststream/actions/workflows/codeql.yml" target="_blank">
    <img src="https://github.com/airtai/faststream/actions/workflows/codeql.yml/badge.svg" alt="CodeQL">
  </a>

  <a href="https://github.com/airtai/faststream/actions/workflows/dependency-review.yaml" target="_blank">
    <img src="https://github.com/airtai/faststream/actions/workflows/dependency-review.yaml/badge.svg" alt="Dependency Review">
  </a>

  <a href="https://github.com/airtai/faststream/blob/main/LICENSE" target="_blank">
    <img src="https://img.shields.io/github/license/airtai/faststream.png" alt="License">
  </a>

  <a href="https://github.com/airtai/faststream/blob/main/CODE_OF_CONDUCT.md" target="_blank">
    <img src="https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg" alt="Code of Conduct">
  </a>

  <a href="https://discord.gg/qFm6aSqq59" target="_blank">
      <img alt="Discord" src="https://img.shields.io/discord/1085457301214855171?logo=discord">
  </a>
</p>

---

## Features

[**FastStream**](https://faststream.airt.ai/latest/) simplifies the process of writing producers and consumers for message queues, handling all the
parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, **FastStream** simplifies your work while keeping the door open for more advanced use cases. Here's a look at the core features that make **FastStream** a go-to framework for modern, data-centric microservices.

- **Multiple Brokers**: **FastStream** provides a unified API to work across multiple message brokers ([**Kafka**](https://kafka.apache.org/), [**RabbitMQ**](https://www.rabbitmq.com/), [**NATS**](https://nats.io/), [**Redis**](https://redis.io/) support)

- [**Pydantic Validation**](#writing-app-code): Leverage [**Pydantic's**](https://docs.pydantic.dev/) validation capabilities to serialize and validate incoming messages

- [**Automatic Docs**](#project-documentation): Stay ahead with automatic [**AsyncAPI**](https://www.asyncapi.com/) documentation

- **Intuitive**: Full-typed editor support makes your development experience smooth, catching errors before they reach runtime

- [**Powerful Dependency Injection System**](#dependencies): Manage your service dependencies efficiently with **FastStream**'s built-in DI system

- [**Testable**](#testing-the-service): Supports in-memory tests, making your CI/CD pipeline faster and more reliable

- **Extensible**: Use extensions for lifespans, custom serialization and middleware

- [**Integrations**](#any-framework): **FastStream** is fully compatible with any HTTP framework you want ([**FastAPI**](#fastapi-plugin) especially)

- [**Built for Automatic Code Generation**](#code-generator): **FastStream** is optimized for automatic code generation using advanced models like GPT and Llama

That's **FastStream** in a nutshell—easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, **FastStream** has got you covered.

---

**Documentation**: <a href="https://faststream.airt.ai/latest/" target="_blank">https://faststream.airt.ai/latest/</a>

---

## History

**FastStream** is a new package based on the ideas and experiences gained from [**FastKafka**](https://github.com/airtai/fastkafka) and [**Propan**](https://github.com/lancetnik/propan). By joining our forces, we picked up the best from both packages and created a unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

---

## Install

**FastStream** works on **Linux**, **macOS**, **Windows** and most **Unix**-style operating systems.
You can install it with `pip` as usual:

```sh
pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]
```

By default **FastStream** uses **PydanticV2** written in **Rust**, but you can downgrade it manually, if your platform has no **Rust** support - **FastStream** will work correctly with **PydanticV1** as well.

---

## Writing app code

**FastStream** brokers provide convenient function decorators `@broker.subscriber`
and `@broker.publisher` to allow you to delegate the actual process of:

- consuming and producing data to Event queues, and

- decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, **FastStream** uses [**Pydantic**](https://docs.pydantic.dev/) to parse input
JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using **FastStream** that consumes data from an incoming data stream and outputs the data to another one:

```python
from faststream import FastStream
from faststream.kafka import KafkaBroker
# from faststream.rabbit import RabbitBroker
# from faststream.nats import NatsBroker
# from faststream.redis import RedisBroker

broker = KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")
# broker = NatsBroker("nats://localhost:4222/")
# broker = RedisBroker("redis://localhost:6379/")

app = FastStream(broker)

@broker.subscriber("in")
@broker.publisher("out")
async def handle_msg(user: str, user_id: int) -> str:
    return f"User: {user_id} - {user} registered"
```

Also, **Pydantic**’s [`BaseModel`](https://docs.pydantic.dev/usage/models/) class allows you
to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

```python
from pydantic import BaseModel, Field, PositiveInt
from faststream import FastStream
from faststream.kafka import KafkaBroker

broker = KafkaBroker("localhost:9092")
app = FastStream(broker)

class User(BaseModel):
    user: str = Field(..., examples=["John"])
    user_id: PositiveInt = Field(..., examples=["1"])

@broker.subscriber("in")
@broker.publisher("out")
async def handle_msg(data: User) -> str:
    return f"User: {data.user} - {data.user_id} registered"
```

---

## Testing the service

The service can be tested using the `TestBroker` context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your `subscriber` and `publisher` decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

```python
# Code above omitted 👆

import pytest
import pydantic
from faststream.kafka import TestKafkaBroker


@pytest.mark.asyncio
async def test_correct():
    async with TestKafkaBroker(broker) as br:
        await br.publish({
            "user": "John",
            "user_id": 1,
        }, "in")

@pytest.mark.asyncio
async def test_invalid():
    async with TestKafkaBroker(broker) as br:
        with pytest.raises(pydantic.ValidationError):
            await br.publish("wrong message", "in")
```

## Running the application

The application can be started using built-in **FastStream** CLI command.

To run the service, use the **FastStream CLI** command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

``` shell
faststream run basic:app
```

After running the command, you should see the following output:

``` shell
INFO     - FastStream app starting...
INFO     - input_data |            - `HandleMsg` waiting for messages
INFO     - FastStream app started successfully! To exit press CTRL+C
```

Also, **FastStream** provides you with a great hot reload feature to improve your Development Experience

``` shell
faststream run basic:app --reload
```

And multiprocessing horizontal scaling feature as well:

``` shell
faststream run basic:app --workers 3
```

You can learn more about **CLI** features [here](https://faststream.airt.ai/latest/getting-started/cli/)

---

## Project Documentation

**FastStream** automatically generates documentation for your project according to the [**AsyncAPI**](https://www.asyncapi.com/) specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - **FastStream** has already created the docs for you!

![HTML-page](https://github.com/airtai/faststream/blob/main/docs/docs/assets/img/AsyncAPI-basic-html-short.png?raw=true)

---

## Dependencies

**FastStream** (thanks to [**FastDepends**](https://lancetnik.github.io/FastDepends/)) has a dependency management system similar to `pytest fixtures` and `FastAPI Depends` at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

```python
from faststream import Depends, Logger

async def base_dep(user_id: int) -> bool:
    return True

@broker.subscriber("in-test")
async def base_handler(user: str,
                       logger: Logger,
                       dep: bool = Depends(base_dep)):
    assert dep is True
    logger.info(user)
```

---

## HTTP Frameworks integrations

### Any Framework

You can use **FastStream** `MQBrokers` without a `FastStream` application.
Just *start* and *stop* them according to your application's lifespan.

```python
from aiohttp import web

from faststream.kafka import KafkaBroker

broker = KafkaBroker("localhost:9092")

@broker.subscriber("test")
async def base_handler(body):
    print(body)

async def start_broker(app):
    await broker.start()

async def stop_broker(app):
    await broker.close()

async def hello(request):
    return web.Response(text="Hello, world")

app = web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)

if __name__ == "__main__":
    web.run_app(app)
```

### **FastAPI** Plugin

Also, **FastStream** can be used as part of **FastAPI**.

Just import a **StreamRouter** you need and declare the message handler with the same `@router.subscriber(...)` and `@router.publisher(...)` decorators.

```python
from fastapi import FastAPI
from pydantic import BaseModel

from faststream.kafka.fastapi import KafkaRouter

router = KafkaRouter("localhost:9092")

class Incoming(BaseModel):
    m: dict

@router.subscriber("test")
@router.publisher("response")
async def hello(m: Incoming):
    return {"response": "Hello, world!"}

app = FastAPI(lifespan=router.lifespan_context)
app.include_router(router)
```

More integration features can be found [here](https://faststream.airt.ai/latest/getting-started/integrations/fastapi/)

---

## Code generator

As evident, **FastStream** is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing [faststream-gen](https://faststream-gen.airt.ai), a Python library that harnesses the power of generative AI to effortlessly generate **FastStream** applications. Simply describe your application requirements, and [faststream-gen](https://faststream-gen.airt.ai) will generate a production-grade **FastStream** project that is ready to deploy in no time.

Save application description inside `description.txt`:
```
Create a FastStream application using localhost broker for testing and use the
default port number.

It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.

While consuming from the topic, increment the value of the data attribute by 1.

Finally, send message to the 'output_data' topic.
```

and run the following command to create a new **FastStream** project:
``` shell
faststream_gen -i description.txt
```

``` shell
✨  Generating a new FastStream application!
 ✔ Application description validated.
 ✔ FastStream app skeleton code generated. Takes around 15 to 45 seconds)...
 ✔ The app and the tests are generated.  around 30 to 90 seconds)...
 ✔ New FastStream project created.
 ✔ Integration tests were successfully completed.
 Tokens used: 10768
 Total Cost (USD): $0.03284
✨  All files were successfully generated!
```

### Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the [faststream-gen](https://faststream-gen.airt.ai) Python library to effortlessly create **FastStream** applications:

- [Cryptocurrency analysis with FastStream](https://faststream-gen.airt.ai/Tutorial/Cryptocurrency_Tutorial/)

---

## Stay in touch

Please show your support and stay in touch by:

- giving our [GitHub repository](https://github.com/airtai/faststream/) a star, and

- joining our [Discord server](https://discord.gg/qFm6aSqq59)

Your support helps us to stay in touch with you and encourages us to
continue developing and improving the framework. Thank you for your
support!

---

## Contributors

Thanks to all of these amazing people who made the project better!

<a href="https://github.com/airtai/faststream/graphs/contributors">
  <img src="https://contrib.rocks/image?repo=airtai/faststream"/>
</a>

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "faststream",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "framework, kafka, message brokers, nats, rabbitmq, redis",
    "author": null,
    "author_email": "airt <info@airt.ai>, Nikita Pastukhov <nikita@pastukhov-dev.ru>",
    "download_url": "https://files.pythonhosted.org/packages/3a/6a/5dc45be590a0d51d08a47ae470b86572b6054459a1842a29da768444f1aa/faststream-0.5.3.tar.gz",
    "platform": null,
    "description": "# FastStream\n\n<b>Effortless event stream integration for your services</b>\n\n---\n\n<p align=\"center\">\n  <a href=\"https://github.com/airtai/faststream/actions/workflows/test.yaml\" target=\"_blank\">\n    <img src=\"https://github.com/airtai/faststream/actions/workflows/test.yaml/badge.svg?branch=main\" alt=\"Test Passing\"/>\n  </a>\n\n  <a href=\"https://coverage-badge.samuelcolvin.workers.dev/redirect/airtai/faststream\" target=\"_blank\">\n      <img src=\"https://coverage-badge.samuelcolvin.workers.dev/airtai/faststream.svg\" alt=\"Coverage\">\n  </a>\n\n  <a href=\"https://www.pepy.tech/projects/faststream\" target=\"_blank\">\n    <img src=\"https://static.pepy.tech/personalized-badge/faststream?period=month&units=international_system&left_color=grey&right_color=green&left_text=downloads/month\" alt=\"Downloads\"/>\n  </a>\n\n  <a href=\"https://pypi.org/project/faststream\" target=\"_blank\">\n    <img src=\"https://img.shields.io/pypi/v/faststream?label=PyPI\" alt=\"Package version\">\n  </a>\n\n  <a href=\"https://pypi.org/project/faststream\" target=\"_blank\">\n    <img src=\"https://img.shields.io/pypi/pyversions/faststream.svg\" alt=\"Supported Python versions\">\n  </a>\n\n  <br/>\n\n  <a href=\"https://github.com/airtai/faststream/actions/workflows/codeql.yml\" target=\"_blank\">\n    <img src=\"https://github.com/airtai/faststream/actions/workflows/codeql.yml/badge.svg\" alt=\"CodeQL\">\n  </a>\n\n  <a href=\"https://github.com/airtai/faststream/actions/workflows/dependency-review.yaml\" target=\"_blank\">\n    <img src=\"https://github.com/airtai/faststream/actions/workflows/dependency-review.yaml/badge.svg\" alt=\"Dependency Review\">\n  </a>\n\n  <a href=\"https://github.com/airtai/faststream/blob/main/LICENSE\" target=\"_blank\">\n    <img src=\"https://img.shields.io/github/license/airtai/faststream.png\" alt=\"License\">\n  </a>\n\n  <a href=\"https://github.com/airtai/faststream/blob/main/CODE_OF_CONDUCT.md\" target=\"_blank\">\n    <img src=\"https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg\" alt=\"Code of Conduct\">\n  </a>\n\n  <a href=\"https://discord.gg/qFm6aSqq59\" target=\"_blank\">\n      <img alt=\"Discord\" src=\"https://img.shields.io/discord/1085457301214855171?logo=discord\">\n  </a>\n</p>\n\n---\n\n## Features\n\n[**FastStream**](https://faststream.airt.ai/latest/) simplifies the process of writing producers and consumers for message queues, handling all the\nparsing, networking and documentation generation automatically.\n\nMaking streaming microservices has never been easier. Designed with junior developers in mind, **FastStream** simplifies your work while keeping the door open for more advanced use cases. Here's a look at the core features that make **FastStream** a go-to framework for modern, data-centric microservices.\n\n- **Multiple Brokers**: **FastStream** provides a unified API to work across multiple message brokers ([**Kafka**](https://kafka.apache.org/), [**RabbitMQ**](https://www.rabbitmq.com/), [**NATS**](https://nats.io/), [**Redis**](https://redis.io/) support)\n\n- [**Pydantic Validation**](#writing-app-code): Leverage [**Pydantic's**](https://docs.pydantic.dev/) validation capabilities to serialize and validate incoming messages\n\n- [**Automatic Docs**](#project-documentation): Stay ahead with automatic [**AsyncAPI**](https://www.asyncapi.com/) documentation\n\n- **Intuitive**: Full-typed editor support makes your development experience smooth, catching errors before they reach runtime\n\n- [**Powerful Dependency Injection System**](#dependencies): Manage your service dependencies efficiently with **FastStream**'s built-in DI system\n\n- [**Testable**](#testing-the-service): Supports in-memory tests, making your CI/CD pipeline faster and more reliable\n\n- **Extensible**: Use extensions for lifespans, custom serialization and middleware\n\n- [**Integrations**](#any-framework): **FastStream** is fully compatible with any HTTP framework you want ([**FastAPI**](#fastapi-plugin) especially)\n\n- [**Built for Automatic Code Generation**](#code-generator): **FastStream** is optimized for automatic code generation using advanced models like GPT and Llama\n\nThat's **FastStream** in a nutshell\u2014easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, **FastStream** has got you covered.\n\n---\n\n**Documentation**: <a href=\"https://faststream.airt.ai/latest/\" target=\"_blank\">https://faststream.airt.ai/latest/</a>\n\n---\n\n## History\n\n**FastStream** is a new package based on the ideas and experiences gained from [**FastKafka**](https://github.com/airtai/fastkafka) and [**Propan**](https://github.com/lancetnik/propan). By joining our forces, we picked up the best from both packages and created a unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.\n\n---\n\n## Install\n\n**FastStream** works on **Linux**, **macOS**, **Windows** and most **Unix**-style operating systems.\nYou can install it with `pip` as usual:\n\n```sh\npip install faststream[kafka]\n# or\npip install faststream[rabbit]\n# or\npip install faststream[nats]\n# or\npip install faststream[redis]\n```\n\nBy default **FastStream** uses **PydanticV2** written in **Rust**, but you can downgrade it manually, if your platform has no **Rust** support - **FastStream** will work correctly with **PydanticV1** as well.\n\n---\n\n## Writing app code\n\n**FastStream** brokers provide convenient function decorators `@broker.subscriber`\nand `@broker.publisher` to allow you to delegate the actual process of:\n\n- consuming and producing data to Event queues, and\n\n- decoding and encoding JSON-encoded messages\n\nThese decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.\n\nAlso, **FastStream** uses [**Pydantic**](https://docs.pydantic.dev/) to parse input\nJSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.\n\nHere is an example Python app using **FastStream** that consumes data from an incoming data stream and outputs the data to another one:\n\n```python\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n# from faststream.rabbit import RabbitBroker\n# from faststream.nats import NatsBroker\n# from faststream.redis import RedisBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n# broker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n# broker = NatsBroker(\"nats://localhost:4222/\")\n# broker = RedisBroker(\"redis://localhost:6379/\")\n\napp = FastStream(broker)\n\n@broker.subscriber(\"in\")\n@broker.publisher(\"out\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n```\n\nAlso, **Pydantic**\u2019s [`BaseModel`](https://docs.pydantic.dev/usage/models/) class allows you\nto define messages using a declarative syntax, making it easy to specify the fields and types of your messages.\n\n```python\nfrom pydantic import BaseModel, Field, PositiveInt\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\nclass User(BaseModel):\n    user: str = Field(..., examples=[\"John\"])\n    user_id: PositiveInt = Field(..., examples=[\"1\"])\n\n@broker.subscriber(\"in\")\n@broker.publisher(\"out\")\nasync def handle_msg(data: User) -> str:\n    return f\"User: {data.user} - {data.user_id} registered\"\n```\n\n---\n\n## Testing the service\n\nThe service can be tested using the `TestBroker` context managers, which, by default, puts the Broker into \"testing mode\".\n\nThe Tester will redirect your `subscriber` and `publisher` decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.\n\nUsing pytest, the test for our service would look like this:\n\n```python\n# Code above omitted \ud83d\udc46\n\nimport pytest\nimport pydantic\nfrom faststream.kafka import TestKafkaBroker\n\n\n@pytest.mark.asyncio\nasync def test_correct():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\n            \"user\": \"John\",\n            \"user_id\": 1,\n        }, \"in\")\n\n@pytest.mark.asyncio\nasync def test_invalid():\n    async with TestKafkaBroker(broker) as br:\n        with pytest.raises(pydantic.ValidationError):\n            await br.publish(\"wrong message\", \"in\")\n```\n\n## Running the application\n\nThe application can be started using built-in **FastStream** CLI command.\n\nTo run the service, use the **FastStream CLI** command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.\n\n``` shell\nfaststream run basic:app\n```\n\nAfter running the command, you should see the following output:\n\n``` shell\nINFO     - FastStream app starting...\nINFO     - input_data |            - `HandleMsg` waiting for messages\nINFO     - FastStream app started successfully! To exit press CTRL+C\n```\n\nAlso, **FastStream** provides you with a great hot reload feature to improve your Development Experience\n\n``` shell\nfaststream run basic:app --reload\n```\n\nAnd multiprocessing horizontal scaling feature as well:\n\n``` shell\nfaststream run basic:app --workers 3\n```\n\nYou can learn more about **CLI** features [here](https://faststream.airt.ai/latest/getting-started/cli/)\n\n---\n\n## Project Documentation\n\n**FastStream** automatically generates documentation for your project according to the [**AsyncAPI**](https://www.asyncapi.com/) specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.\n\nThe availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - **FastStream** has already created the docs for you!\n\n![HTML-page](https://github.com/airtai/faststream/blob/main/docs/docs/assets/img/AsyncAPI-basic-html-short.png?raw=true)\n\n---\n\n## Dependencies\n\n**FastStream** (thanks to [**FastDepends**](https://lancetnik.github.io/FastDepends/)) has a dependency management system similar to `pytest fixtures` and `FastAPI Depends` at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.\n\n```python\nfrom faststream import Depends, Logger\n\nasync def base_dep(user_id: int) -> bool:\n    return True\n\n@broker.subscriber(\"in-test\")\nasync def base_handler(user: str,\n                       logger: Logger,\n                       dep: bool = Depends(base_dep)):\n    assert dep is True\n    logger.info(user)\n```\n\n---\n\n## HTTP Frameworks integrations\n\n### Any Framework\n\nYou can use **FastStream** `MQBrokers` without a `FastStream` application.\nJust *start* and *stop* them according to your application's lifespan.\n\n```python\nfrom aiohttp import web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\nasync def start_broker(app):\n    await broker.start()\n\nasync def stop_broker(app):\n    await broker.close()\n\nasync def hello(request):\n    return web.Response(text=\"Hello, world\")\n\napp = web.Application()\napp.add_routes([web.get(\"/\", hello)])\napp.on_startup.append(start_broker)\napp.on_cleanup.append(stop_broker)\n\nif __name__ == \"__main__\":\n    web.run_app(app)\n```\n\n### **FastAPI** Plugin\n\nAlso, **FastStream** can be used as part of **FastAPI**.\n\nJust import a **StreamRouter** you need and declare the message handler with the same `@router.subscriber(...)` and `@router.publisher(...)` decorators.\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\nclass Incoming(BaseModel):\n    m: dict\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming):\n    return {\"response\": \"Hello, world!\"}\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n```\n\nMore integration features can be found [here](https://faststream.airt.ai/latest/getting-started/integrations/fastapi/)\n\n---\n\n## Code generator\n\nAs evident, **FastStream** is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing [faststream-gen](https://faststream-gen.airt.ai), a Python library that harnesses the power of generative AI to effortlessly generate **FastStream** applications. Simply describe your application requirements, and [faststream-gen](https://faststream-gen.airt.ai) will generate a production-grade **FastStream** project that is ready to deploy in no time.\n\nSave application description inside `description.txt`:\n```\nCreate a FastStream application using localhost broker for testing and use the\ndefault port number.\n\nIt should consume messages from the 'input_data' topic, where each message is a\nJSON encoded object containing a single attribute: 'data'.\n\nWhile consuming from the topic, increment the value of the data attribute by 1.\n\nFinally, send message to the 'output_data' topic.\n```\n\nand run the following command to create a new **FastStream** project:\n``` shell\nfaststream_gen -i description.txt\n```\n\n``` shell\n\u2728  Generating a new FastStream application!\n \u2714 Application description validated.\n \u2714 FastStream app skeleton code generated. Takes around 15 to 45 seconds)...\n \u2714 The app and the tests are generated.  around 30 to 90 seconds)...\n \u2714 New FastStream project created.\n \u2714 Integration tests were successfully completed.\n Tokens used: 10768\n Total Cost (USD): $0.03284\n\u2728  All files were successfully generated!\n```\n\n### Tutorial\n\nWe also invite you to explore our tutorial, where we will guide you through the process of utilizing the [faststream-gen](https://faststream-gen.airt.ai) Python library to effortlessly create **FastStream** applications:\n\n- [Cryptocurrency analysis with FastStream](https://faststream-gen.airt.ai/Tutorial/Cryptocurrency_Tutorial/)\n\n---\n\n## Stay in touch\n\nPlease show your support and stay in touch by:\n\n- giving our [GitHub repository](https://github.com/airtai/faststream/) a star, and\n\n- joining our [Discord server](https://discord.gg/qFm6aSqq59)\n\nYour support helps us to stay in touch with you and encourages us to\ncontinue developing and improving the framework. Thank you for your\nsupport!\n\n---\n\n## Contributors\n\nThanks to all of these amazing people who made the project better!\n\n<a href=\"https://github.com/airtai/faststream/graphs/contributors\">\n  <img src=\"https://contrib.rocks/image?repo=airtai/faststream\"/>\n</a>\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "FastStream: the simplest way to work with a messaging queues",
    "version": "0.5.3",
    "project_urls": {
        "Discord": "https://discord.gg/qFm6aSqq59",
        "Documentation": "https://faststream.airt.ai/latest/getting-started/",
        "Homepage": "https://faststream.airt.ai/latest/",
        "Source": "https://github.com/airtai/FastStream",
        "Tracker": "https://github.com/airtai/FastStream/issues"
    },
    "split_keywords": [
        "framework",
        " kafka",
        " message brokers",
        " nats",
        " rabbitmq",
        " redis"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1614d275acca083d4a00eac2c4fba62dcdb5d0ba4c69546e65c33994b30f4ac5",
                "md5": "294bf5ccd58a66b245031efb32fbdb1b",
                "sha256": "ea72baff81b117a9d4b3569cb4c1ac5f6288d4d9f362c5b09ce7d1575e5c0d3b"
            },
            "downloads": -1,
            "filename": "faststream-0.5.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "294bf5ccd58a66b245031efb32fbdb1b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 307376,
            "upload_time": "2024-04-23T12:16:38",
            "upload_time_iso_8601": "2024-04-23T12:16:38.547672Z",
            "url": "https://files.pythonhosted.org/packages/16/14/d275acca083d4a00eac2c4fba62dcdb5d0ba4c69546e65c33994b30f4ac5/faststream-0.5.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3a6a5dc45be590a0d51d08a47ae470b86572b6054459a1842a29da768444f1aa",
                "md5": "be360534e161522b330bc2a906eb7141",
                "sha256": "e4b2f292a163e5ac8598011a666aa3033f49e20262ea9d71732968b404cb3d97"
            },
            "downloads": -1,
            "filename": "faststream-0.5.3.tar.gz",
            "has_sig": false,
            "md5_digest": "be360534e161522b330bc2a906eb7141",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 234678,
            "upload_time": "2024-04-23T12:16:41",
            "upload_time_iso_8601": "2024-04-23T12:16:41.358867Z",
            "url": "https://files.pythonhosted.org/packages/3a/6a/5dc45be590a0d51d08a47ae470b86572b6054459a1842a29da768444f1aa/faststream-0.5.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-23 12:16:41",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "airtai",
    "github_project": "FastStream",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "faststream"
}
        
Elapsed time: 0.24515s