pythonsessionpylonspyramidbeaker

How do I save values to an anonymous cookie based session in Pyramid using Beaker


I have a Pyramid application using Beaker Encrypted cookie sessions. I can log a user in using a RequestWithUserAttribute, pyramid.security.authenticated_userid(), remember() and forget() just fine.

However, the majority of users will never log in, and there is a specific value I'd like to save in a cookie (encrypted if at all possible) that the user has given then site (their location, or any string for that matter).

I cannot discover how to set more than the principal for a session using the remember() function, and I'd prefer not to send my own Set-Cookie headers, let alone deal with the encryption of the data myself.

I have found that you can pass keyword arguments to remember():

remember(request, principal, *kw)

But when I try to send any extra values I continuously run into an error.

Ideally I would expect something like this:

remember(request, 'public', {'location':request.params.get('location')})

Is this even the correct route?


Solution

  • Sessions and Authentication in Pyramid (and in general) are disjoint concepts. There are a lot of people who learn the way to store the authenticated user "is in a session", but in no way is this a requirement. The point of a session is to store arbitrary data for a visitor to your site across requests. That could be the fact that they are logged in or it could be your random strings.

    The point is you can store random stuff in the session. It is available in Pyramid (after you've setup the session_factory on the Configurator) directly on the request object via request.session.

    request.session['mykey'] = 'some random value'
    

    This does not require you to use authentication, remember/forget, or anything other than a session factory.

    https://docs.pylonsproject.org/projects/pyramid/en/1.2-branch/narr/sessions.html