Sessions in Inspira

Getting Started

To begin, follow these commands to install Inspira and set up the project directories:

$ mkdir sessions
$ cd sessions
$ python -m venv .venv
$ source .venv/bin/activate
$ pip install inspira
$ inspira init

Generating Controller

Generate necessary resources for your project by running the following command:

$ inspira new controller session

Session Middleware

To enable the SessionMiddleware in your application, open the file and include the following code:

from inspira.middlewares.sessions import SessionMiddleware

# Initialize SessionMiddleware with the app's secret key
session = SessionMiddleware()

# Add the session middleware to the app

Session Config

To modify the default session configuration, such as updating the max_age, follow these steps:

# Update the max age for sessions
app.config['SESSION_MAX_AGE'] = 3600

You can override various default session configuration options, including:


Controller Modifications

Navigate to the file and implement the following changes:

from inspira.decorators.http_methods import get
from inspira.decorators.path import path
from inspira.requests import Request
from inspira.responses import HttpResponse

class SessionController:

    async def index(self, request: Request):
        request.set_session("hayri", "yes")

        return HttpResponse("Session set successfully")

    async def get_session(self, request: Request):
        session = request.session

        if "hayri" in session:
            return HttpResponse("Hayri was in the session")
            return HttpResponse("Hayri was not in the session")

    async def remove_session(self, request: Request):

        return HttpResponse("Hayri was removed from the session")

When you access http://localhost:8000/sessions, the session with the key named hayri will be established.

Session is set

Upon visiting http://localhost:8000/sessions/get, you will observe that the session has been successfully set.

Getting the session

Proceed to http://localhost:8000/sessions/remove, and the session will be promptly removed.

Removing the session

If you return to http://localhost:8000/sessions/get, you will notice that the session no longer exists.

Removing the session


In conclusion, this article provided a comprehensive overview of session management in Inspira, guiding you through the process of setting, retrieving, and removing sessions with clarity and example code.

The code is available on GitHub

Happy coding!