fastapi-mqtt icon indicating copy to clipboard operation
fastapi-mqtt copied to clipboard

Using Pydantic models for messages

Open bitplane opened this issue 1 year ago • 4 comments

Are there any plans to make this library more like FastAPI with regard to tightly defined models and being more opinionated about the default way to do things? If so, where would we start?

I'm thinking maybe:

  • Moving on_connect, on_message and so on to an advanced example rather than the main one
  • Adding a PayloadModel to the the subscribe decorator.
  • Add a decorator (@topics?) for outbound traffic, with the model as a hint in the payload field
  • Adding an error decorator, that is called when an exception is raised when constructing
  • A decorator for a Last Will and Testament function
  • A router class so the code can be nicely split up into different files, like in FastAPI
  • Integrate support for encoding/decoding Pydantic models to lightweight transport formats rather than json (bencoding, bson, protobuf, cson, asn.1 or cap'n proto?)

But I'm a noob here. Would there be any love for the models stuff? And where's best to start?

bitplane avatar Mar 02 '23 02:03 bitplane

you can split your code in multiple files as you do in fastapi https://fastapi.tiangolo.com/tutorial/bigger-applications/ you need to make functions for publishing and subscribing the event

kalmastenitin avatar Mar 28 '23 11:03 kalmastenitin

I want to tightly define types of messages sent to and from topics using pydantic basemodels.

bitplane avatar Mar 29 '23 15:03 bitplane

I want to tightly define types of messages sent to and from topics using pydantic basemodels.

Can you show what exactly you want?

kalmastenitin avatar Mar 30 '23 07:03 kalmastenitin

Not sure, something like this maybe?

class MyItem(BaseModel):
    value: int

@mq.subscribe("topic")
async def topic(item: MyItem):
    print(f"item has a value of {item.value}")

bitplane avatar Mar 31 '23 04:03 bitplane