Working with Middlewares and Events

As Batman's application grew more complex, Robyn taught him about middlewares, startup and shutdown events, and even working with WebSockets. Batman learned how to create functions that could execute before or after a request, manage the application's life cycle, and handle real-time communication with clients using WebSockets.

Handling Events

Batman discovered that he could add startup and shutdown events to manage his application's life cycle. He added the following code to define these events:

Batman was excited to learn that he could add events as functions as well as decorators.

Request

GET
/hello_world
async def startup_handler():
  print("Starting up")

app.startup_handler(startup_handler)


For an asynchronous request, Batman used:

Request

GET
/hello_world
@app.get("/")
async def h(request):
    return "Hello, world"

POST/http_requests

Handling Middlewares

Batman learned to use both sync and async functions for middlewares. He wrote the following code to add a middleware that would execute before and after each request:

Request

POST
/http_requests
@app.before_request("/")
async def hello_before_request(request: Request):
    request.headers["before"] = "sync_before_request"
    print(request)

@app.after_request("/")
def hello_after_request(response: Response):
    response.headers.set("after", "sync_after_request"")
    print(response)

What's next?

Robyn - Great, you're now familiar with the certain advanced concepts of Robyn. Middlewares serve the base of

Batman - "Authentication! I want to learn about authentication. I want to make sure that only the right people can access my application."

Robyn - Yes, Authentication!