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 main.py 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
app.add_middleware(session)

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:

app.config["SESSION_COOKIE_NAME"]
app.config["SESSION_MAX_AGE"]
app.config["SESSION_COOKIE_DOMAIN"]
app.config["SESSION_COOKIE_PATH"]
app.config["SESSION_COOKIE_HTTPONLY"]
app.config["SESSION_COOKIE_SECURE"]
app.config["SESSION_COOKIE_SAMESITE"]

Controller Modifications

Navigate to the sessions_controller.py 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


@path("/sessions")
class SessionController:

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

        return HttpResponse("Session set successfully")

    @get("/get")
    async def get_session(self, request: Request):
        session = request.session

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

    @get("/remove")
    async def remove_session(self, request: Request):
        request.remove_session("hayri")

        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

Conclusion

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!