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:
<import py="moya.libs.sessions"/>
The session library should be installed and mounted on /
as follows:
<install name="session" lib="moya.session" mount="/"/>
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:
<dict dst=".session.cart" if="'cart' not in .session"><list dst="cart"/></dict>
This code creates a list called cart
in .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:
<append src=".session.cart" value="'Asahi beer'"/>
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 .session_key
.
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:
{% cache key=.session_key %}<!-- calculate something expensive for the user -->{% endcache %}
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 expire
is 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:
[settings:session]expire = 24h