Jacob Banks

Jacob Banks

1650424605

Asynchronous Event Dispatching/Handling Library for FastAPI and Starlette

FastAPI Events

An event dispatching/handling library for FastAPI, and Starlette.

Features:

  • straightforward API to emit events anywhere in your code
  • events are handled after responses are returned (doesn't affect response time)
  • supports event piping to remote queues
  • powerful built-in handlers to handle events locally and remotely
  • coroutine functions (async def) are the first-class citizen
  • write your handlers, never be limited to just what fastapi_events provides
  • (>=0.3.0) supports event payload validation via Pydantic (See here)

Installation

pip install fastapi-events

To use it with AWS handlers, install:

pip install fastapi-events[aws]

Usage

fastapi-events supports both FastAPI and Starlette. To use it, simply configure it as middleware.

Configuring fastapi-events for FastAPI:

from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import JSONResponse

from fastapi_events.dispatcher import dispatch
from fastapi_events.middleware import EventHandlerASGIMiddleware
from fastapi_events.handlers.local import local_handler


app = FastAPI()
app.add_middleware(EventHandlerASGIMiddleware, 
                   handlers=[local_handler])   # registering handler(s)


@app.get("/")
def index(request: Request) -> JSONResponse:
    dispatch("my-fancy-event", payload={"id": 1})  # Emit events anywhere in your code
    return JSONResponse()    

Configuring fastapi-events for Starlette:

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse

from fastapi_events.dispatcher import dispatch
from fastapi_events.handlers.local import local_handler
from fastapi_events.middleware import EventHandlerASGIMiddleware

app = Starlette(middleware=[
    Middleware(EventHandlerASGIMiddleware,
               handlers=[local_handler])  # registering handlers
])

@app.route("/")
async def root(request: Request) -> JSONResponse:
    dispatch("new event", payload={"id": 1})   # Emit events anywhere in your code
    return JSONResponse()

Dispatching events

Events can be dispatched anywhere in the code, as long as they are dispatched before a response is made.

# anywhere in code

from fastapi_events.dispatcher import dispatch

dispatch(
    "cat-requested-a-fish",  # Event name, accepts any valid string
    payload={"cat_id": "fd375d23-b0c9-4271-a9e0-e028c4cd7230"}  # Event payload, accepts any arbitrary data
)

dispatch("a_cat_is_spotted")  # This works too!

Event Payload Validation With Pydantic

Event payload validation is possible since version 0.3.0. To enable, simply register a Pydantic models with the corresponding event name.

import uuid
from enum import Enum
from datetime import datetime

from pydantic import BaseModel
from fastapi_events.registry.payload_schema import registry as payload_schema


class UserEvents(Enum):
    SIGNED_UP = "USER_SIGNED_UP"
    ACTIVATED = "USER_ACTIVATED"


# Registering your event payload schema
@payload_schema.register(event_name=UserEvents.SIGNED_UP)
class SignUpPayload(BaseModel):
    user_id: uuid.UUID
    created_at: datetime

Wildcard in event name is currently not supported

Payload will be validated automatically without any changes made while invoking the dispatcher.

# Events with payload schema registered
dispatch(UserEvents.SIGNED_UP)  # raises ValidationError, missing payload
dispatch(UserEvents.SIGNED_UP,
         {"user_id": "9e79cdbb-b216-40f7-9a05-20d223dee89a"})  # raises ValidationError, missing `created_at`
dispatch(UserEvents.SIGNED_UP,
         {"user_id": "9e79cdbb-b216-40f7-9a05-20d223dee89a", created_at: datetime.utcnow()})  # OK!

# Events without payload schema -> No validation will be performed
dispatch(UserEvents.ACTIVATED,
         {"user_id": "9e79cdbb-b216-40f7-9a05-20d223dee89a"})  # OK! no validation will be performed

Reminder: payload validation is optional. Payload of events without its schema registered will not be validated.

Handling Events

Handle events locally

The flexibility of fastapi-events allows us to customise how the events should be handled. For starters, you might want to handle your events locally.

# ex: in handlers.py

from fastapi_events.handlers.local import local_handler
from fastapi_events.typing import Event


@local_handler.register(event_name="cat*")
def handle_all_cat_events(event: Event):
    """
    this handler will match with an events prefixed with `cat`.
    ex: "cat_eats_a_fish", "cat_is_cute", etc
    """
    # the `event` argument is nothing more than a tuple of event name and payload
    event_name, payload = event

    # TODO do anything you'd like with the event


@local_handler.register(event_name="cat*")  # Tip: You can register several handlers with the same event name
def handle_all_cat_events_another_way(event: Event):
    pass


@local_handler.register(event_name="*")
async def handle_all_events(event: Event):
    # event handlers can be coroutine function too (`async def`)
    pass

Piping Events To Remote Queues

For larger projects, you might have services dedicated to handling events separately.

For instance, fastapi-events comes with AWS SQS forwarder to forward events to a remote queue.

Register SQSForwardHandler as handlers:

app = FastAPI()
app.add_middleware(EventHandlerASGIMiddleware, 
                   handlers=[SQSForwardHandler(queue_url="test-queue",
                                               region_name="eu-central-1")])   # registering handler(s)

Start dispatching events! Events will be serialised into JSON format by default:

["event name", {"payload": "here is the payload"}]

Tip: to pipe events to multiple queues, provide multiple handlers while adding EventHandlerASGIMiddleware.

Built-in handlers

Here is a list of built-in event handlers:

LocalHandler / local_handler:

  • import from fastapi_events.handlers.local
  • for handling events locally. See examples above
  • event name pattern matching is done using Unix shell-style matching (fnmatch)

SQSForwardHandler:

  • import from fastapi_events.handlers.aws
  • to forward events to an AWS SQS queue

EchoHandler:

  • import from fastapi_events.handlers.echo
  • to forward events to stdout with pprint. Great for debugging purpose

Creating your own handler

Creating your own handler is nothing more than inheriting from the BaseEventHandler class in fastapi_events.handlers.base.

To handle events, fastapi_events calls one of these methods, in the following priority order:

handle_many(events): The coroutine function should expect the backlog of the events collected.

handle(event): In cases where handle_many() weren't defined in your custom handler, handle() will be called by iterating through the events in the backlog.

from typing import Iterable

from fastapi_events.typing import Event
from fastapi_events.handlers.base import BaseEventHandler


class MyOwnEventHandler(BaseEventHandler):
    async def handle(self, event: Event) -> None:
        """
        Handle events one by one
        """
        pass

    async def handle_many(self, events: Iterable[Event]) -> None:
        """
        Handle events by batch
        """
        pass

Cookbook

1) Suppressing Events / Disabling dispatch() Globally

In case you want to suppress events globally especially during testing, you can do so without having to mock or patch the dispatch() function. Simple set the environment variable FASTAPI_EVENTS_DISABLE_DISPATCH to 1, True or any truthy values.

2) Validating Event Payload During Dispatch

Requires Pydantic, which comes with FastAPI. If you're using Starlette, you might need to install Pydantic

See Event Payload Validation With Pydantic

FAQs:

I'm getting LookupError when dispatch() is used:

    def dispatch(event_name: str, payload: Optional[Any] = None) -> None:
>       q: Deque[Event] = event_store.get()
E       LookupError: <ContextVar name='fastapi_context' at 0x400a1f12b0>

Answer:

dispatch() relies on ContextVars to work properly. There are many reasons why LookupError can occur. A common reason is dispatch() is called outside the request-response lifecycle of FastAPI/Starlette, such as calling dispatch() after a response has been returned.

If you're getting this during testing, you may consider disabling dispatch() during testing. See Suppressing Events / Disabling dispatch() Globally for details.

My event handlers are not registered / Local handlers are not being executed:

Answer:

Make sure the module where your local event handlers are defined is loaded during runtime. A simple fix is to import the module in your __init__.py. This will ensure the modules are properly loaded during runtime.

Feedback, Questions?

Any form of feedback and questions are welcome! Please create an issue here.

Download Details: 
Author: melvinkcx
Source Code: https://github.com/melvinkcx/fastapi-events 
License: MIT
#python #starlette #fastapi

What is GEEK

Buddha Community

Asynchronous Event Dispatching/Handling Library for FastAPI and Starlette
Jacob Banks

Jacob Banks

1650424605

Asynchronous Event Dispatching/Handling Library for FastAPI and Starlette

FastAPI Events

An event dispatching/handling library for FastAPI, and Starlette.

Features:

  • straightforward API to emit events anywhere in your code
  • events are handled after responses are returned (doesn't affect response time)
  • supports event piping to remote queues
  • powerful built-in handlers to handle events locally and remotely
  • coroutine functions (async def) are the first-class citizen
  • write your handlers, never be limited to just what fastapi_events provides
  • (>=0.3.0) supports event payload validation via Pydantic (See here)

Installation

pip install fastapi-events

To use it with AWS handlers, install:

pip install fastapi-events[aws]

Usage

fastapi-events supports both FastAPI and Starlette. To use it, simply configure it as middleware.

Configuring fastapi-events for FastAPI:

from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import JSONResponse

from fastapi_events.dispatcher import dispatch
from fastapi_events.middleware import EventHandlerASGIMiddleware
from fastapi_events.handlers.local import local_handler


app = FastAPI()
app.add_middleware(EventHandlerASGIMiddleware, 
                   handlers=[local_handler])   # registering handler(s)


@app.get("/")
def index(request: Request) -> JSONResponse:
    dispatch("my-fancy-event", payload={"id": 1})  # Emit events anywhere in your code
    return JSONResponse()    

Configuring fastapi-events for Starlette:

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse

from fastapi_events.dispatcher import dispatch
from fastapi_events.handlers.local import local_handler
from fastapi_events.middleware import EventHandlerASGIMiddleware

app = Starlette(middleware=[
    Middleware(EventHandlerASGIMiddleware,
               handlers=[local_handler])  # registering handlers
])

@app.route("/")
async def root(request: Request) -> JSONResponse:
    dispatch("new event", payload={"id": 1})   # Emit events anywhere in your code
    return JSONResponse()

Dispatching events

Events can be dispatched anywhere in the code, as long as they are dispatched before a response is made.

# anywhere in code

from fastapi_events.dispatcher import dispatch

dispatch(
    "cat-requested-a-fish",  # Event name, accepts any valid string
    payload={"cat_id": "fd375d23-b0c9-4271-a9e0-e028c4cd7230"}  # Event payload, accepts any arbitrary data
)

dispatch("a_cat_is_spotted")  # This works too!

Event Payload Validation With Pydantic

Event payload validation is possible since version 0.3.0. To enable, simply register a Pydantic models with the corresponding event name.

import uuid
from enum import Enum
from datetime import datetime

from pydantic import BaseModel
from fastapi_events.registry.payload_schema import registry as payload_schema


class UserEvents(Enum):
    SIGNED_UP = "USER_SIGNED_UP"
    ACTIVATED = "USER_ACTIVATED"


# Registering your event payload schema
@payload_schema.register(event_name=UserEvents.SIGNED_UP)
class SignUpPayload(BaseModel):
    user_id: uuid.UUID
    created_at: datetime

Wildcard in event name is currently not supported

Payload will be validated automatically without any changes made while invoking the dispatcher.

# Events with payload schema registered
dispatch(UserEvents.SIGNED_UP)  # raises ValidationError, missing payload
dispatch(UserEvents.SIGNED_UP,
         {"user_id": "9e79cdbb-b216-40f7-9a05-20d223dee89a"})  # raises ValidationError, missing `created_at`
dispatch(UserEvents.SIGNED_UP,
         {"user_id": "9e79cdbb-b216-40f7-9a05-20d223dee89a", created_at: datetime.utcnow()})  # OK!

# Events without payload schema -> No validation will be performed
dispatch(UserEvents.ACTIVATED,
         {"user_id": "9e79cdbb-b216-40f7-9a05-20d223dee89a"})  # OK! no validation will be performed

Reminder: payload validation is optional. Payload of events without its schema registered will not be validated.

Handling Events

Handle events locally

The flexibility of fastapi-events allows us to customise how the events should be handled. For starters, you might want to handle your events locally.

# ex: in handlers.py

from fastapi_events.handlers.local import local_handler
from fastapi_events.typing import Event


@local_handler.register(event_name="cat*")
def handle_all_cat_events(event: Event):
    """
    this handler will match with an events prefixed with `cat`.
    ex: "cat_eats_a_fish", "cat_is_cute", etc
    """
    # the `event` argument is nothing more than a tuple of event name and payload
    event_name, payload = event

    # TODO do anything you'd like with the event


@local_handler.register(event_name="cat*")  # Tip: You can register several handlers with the same event name
def handle_all_cat_events_another_way(event: Event):
    pass


@local_handler.register(event_name="*")
async def handle_all_events(event: Event):
    # event handlers can be coroutine function too (`async def`)
    pass

Piping Events To Remote Queues

For larger projects, you might have services dedicated to handling events separately.

For instance, fastapi-events comes with AWS SQS forwarder to forward events to a remote queue.

Register SQSForwardHandler as handlers:

app = FastAPI()
app.add_middleware(EventHandlerASGIMiddleware, 
                   handlers=[SQSForwardHandler(queue_url="test-queue",
                                               region_name="eu-central-1")])   # registering handler(s)

Start dispatching events! Events will be serialised into JSON format by default:

["event name", {"payload": "here is the payload"}]

Tip: to pipe events to multiple queues, provide multiple handlers while adding EventHandlerASGIMiddleware.

Built-in handlers

Here is a list of built-in event handlers:

LocalHandler / local_handler:

  • import from fastapi_events.handlers.local
  • for handling events locally. See examples above
  • event name pattern matching is done using Unix shell-style matching (fnmatch)

SQSForwardHandler:

  • import from fastapi_events.handlers.aws
  • to forward events to an AWS SQS queue

EchoHandler:

  • import from fastapi_events.handlers.echo
  • to forward events to stdout with pprint. Great for debugging purpose

Creating your own handler

Creating your own handler is nothing more than inheriting from the BaseEventHandler class in fastapi_events.handlers.base.

To handle events, fastapi_events calls one of these methods, in the following priority order:

handle_many(events): The coroutine function should expect the backlog of the events collected.

handle(event): In cases where handle_many() weren't defined in your custom handler, handle() will be called by iterating through the events in the backlog.

from typing import Iterable

from fastapi_events.typing import Event
from fastapi_events.handlers.base import BaseEventHandler


class MyOwnEventHandler(BaseEventHandler):
    async def handle(self, event: Event) -> None:
        """
        Handle events one by one
        """
        pass

    async def handle_many(self, events: Iterable[Event]) -> None:
        """
        Handle events by batch
        """
        pass

Cookbook

1) Suppressing Events / Disabling dispatch() Globally

In case you want to suppress events globally especially during testing, you can do so without having to mock or patch the dispatch() function. Simple set the environment variable FASTAPI_EVENTS_DISABLE_DISPATCH to 1, True or any truthy values.

2) Validating Event Payload During Dispatch

Requires Pydantic, which comes with FastAPI. If you're using Starlette, you might need to install Pydantic

See Event Payload Validation With Pydantic

FAQs:

I'm getting LookupError when dispatch() is used:

    def dispatch(event_name: str, payload: Optional[Any] = None) -> None:
>       q: Deque[Event] = event_store.get()
E       LookupError: <ContextVar name='fastapi_context' at 0x400a1f12b0>

Answer:

dispatch() relies on ContextVars to work properly. There are many reasons why LookupError can occur. A common reason is dispatch() is called outside the request-response lifecycle of FastAPI/Starlette, such as calling dispatch() after a response has been returned.

If you're getting this during testing, you may consider disabling dispatch() during testing. See Suppressing Events / Disabling dispatch() Globally for details.

My event handlers are not registered / Local handlers are not being executed:

Answer:

Make sure the module where your local event handlers are defined is loaded during runtime. A simple fix is to import the module in your __init__.py. This will ensure the modules are properly loaded during runtime.

Feedback, Questions?

Any form of feedback and questions are welcome! Please create an issue here.

Download Details: 
Author: melvinkcx
Source Code: https://github.com/melvinkcx/fastapi-events 
License: MIT
#python #starlette #fastapi

studio52 dubai

studio52 dubai

1621850716

7 Tips for a Successful Live Event Coverage - Studio 52

Live events have been a growing trend in the events industry this past year, offering many businesses a much-needed lifeline. Read on for our simple tips to planning your virtual event

#event coverage services #event photography #event video production #event videography #event coverage services #event photography

How much does it cost to develop an app for the event planning business?

Event planning & management app is the generic term for a wide range of mobile app products that are used in the management of professional and academic conferences, trade exhibitions, conventions, and events such as Continuing Professional Development meetings.

Development Cost to build an Event Planning & Management App:

Based on the number of hours invested, features, and technologies involved, you can determine a rough estimate of Event Planning or Management app development cost. Cost depends on various factors such as follows.

• Basic & Advance Features

• Technology used

• Chosen Platform (iOS & Android)

• The Location of the app development center

• Mobile App complexity

• Numbers of hours invested in Project

The cost to create such an app can be as high as the number of integrated technologies. However, an app with basic features is certain to cost somewhere around $10,000 to $35,000 for single platforms (Android or iOS). If you want to make an app for various platforms then the cost will be vary based on features, location, development team, etc factors.

Best Event Planning & Management App Development Company:

Event Management apps streamline the entry process for events. Save your precious time for a smooth experience and devote time for more significant activities such as increasing revenue with a mobile app from AppClues Infotech, a top Events & Exhibitions App Development Company based in the USA and offer the best services across the world.

Save your time and money with their cost-effective mobile apps to easily collaborate with the participants of the events. Real-time chats help to carry out video conferencing with both the participants and the employees as well. Their mobile apps increase the efficiency of multiple events by sending important messages to the participants with a single click.

Offering services that make events successful:

  • Corporate events
  • Conferences
  • Trade shows
  • Sports and entertainment
  • Custom event schedule app development

Incorporate features that elevate experiences

  • Event creation
  • Event search
  • Event calendar
  • Ticket booking
  • Photo sharing
  • GPS
  • Push notification
  • Chatbot
  • Messaging
  • In-app payment
  • News & social feeds
  • In-app analytics

#how to develop an event app #event management app development company #custom event management app development #how to build an event planning app #develop a mobile app for events #cost to build a event management app

How much does it cost to build a virtual event application in 2021?

A Brief about Virtual Events
After the Covid-19 virtual event trend rising and now the demand has more increased. Digital activities are events held online in their most simplistic sense. Virtual events use web-based platforms to connect thousands of people worldwide.

Virtual events can cover anything, including individual events, but generally, four kinds of virtual events are available: virtual conferences, webinars, hybrid internal & external events. Google Meet, Evia, Digitell, ON 24, Zoom, GoToMeeting and more are among the top virtual event platforms.

Cost to Build a Virtual Event Application in 2021
The development cost of the application mostly depends on the features of a mobile application. The approx cost to build a virtual event app between $20,000 to $50,000 for a single platform (Android & iOS). It may go high if you choose the advanced technology and features while developing.

Best Virtual Event App Development Company

AppClues Infotech is a pioneer in providing innovative & unique mobile app solutions that offer impressive results and can make things easier. If you are looking forward to creating an application that can host your virtual events and meetings without gathering your team in the office then you surely are in the right place.

Why Choose AppClues Infotech for Virtual Event App Development?

• Innovative Solutions
• Round the Clock Availability
• Latest Technology
• Experience in the Field
• On-Time Delivery

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#virtual event app development #a complete guide to building a virtual event app #best mobile event apps development company #mobile event apps development company in usa #top virtual event apps development company in usa #virtual event platform development guide

Event Planning App Development

A manual search for ticket holders in an event leads to long queues and a delay in start time. This affects the credibility of the event management company. With an event management app, you can have seamless interactions; you can effortlessly communicate with event attendees. Also, event apps facilitate enhanced networking at events

Do you wish to have an event management app of your own?

DataIT Solutions are here to serve you with the best Event booking application for Android and iPhone. Having years of in-depth experience in mobile application development, we have been delivering the top class solutions for app development as per user prerequisites each time. Our mobile developers having all the skills to provide you a customized event application and can work on any kind of Mobile App Development for Event Booking.

What can you expect while you work with us for Mobile Event Mobile App Development?

  • Experienced Team of Web and Graphics Designers
  • Event App Development Team with rich exposure to Event Planning and Event Management App for iOS, Android, and other platforms
  • Consultative and Agile approach to Project Management
  • Cost-Effective and Custom Business Model to meet your Requirements
  • Effective tools of communication providing you detailed updates on every stage of your Project by your convenient mode of communication at your preferred time.

Excited to know more about the scope of your project? Send us an email for a free quote on Event Mobile App Development for your requirement to sales@dataitsolutions.com.

#event planning app development #event planning app developer #event app developer #event app development #event app #app development