The Moya Sessions library manages sessions. A session is persistent data associated with a single browser session, and may be used for storing data across requests.
The Moya Sessions library is built in to Moya and may be imported via its Python path as follows:
The session library should be installed and mounted on
/ as follows:
Session information is stored in a dictionary called
.session. You may populate this with any data you wish to stored. At the end of a successful request, this data will be written to the database. Here's an example of how you might implement a shopping cart:
This code creates a list called
.session where we can store the products a user clicks on. To add a product we can simply append to
.session.cart. Here's an example:
When the user visits the checkout page, you can then list all the products in their shopping cart.
The session is identified by setting a randomly generated cookie. You can inspect this value in the context with
The session key may be used when caching to ensure that something is cached for user's session. This is useful if you have some content related to the user which is slow to generate, but won't change during a browser session. Here's how you might user that in a template:
There is currently one setting for the Session library;
expire should be a timespan which indicates how long the session should persist before it expires. If the user makes no requests in this time, the session will be reset to an empty dictionary.
The default value for
1h which will cause the session to expires after 1 hour. Here's what you would add to your settings to raise this to 24 hours: