pyramid.session¶
-
signed_serialize(data, secret)[source]¶ Serialize any pickleable structure (
data) and sign it using thesecret(must be a string). Return the serialization, which includes the signature as its first 40 bytes. Thesigned_deserializemethod will deserialize such a value.This function is useful for creating signed cookies. For example:
cookieval = signed_serialize({'a':1}, 'secret') response.set_cookie('signed_cookie', cookieval)
-
signed_deserialize(serialized, secret, hmac=<module 'hmac' from '/usr/lib/python3.6/hmac.py'>)[source]¶ Deserialize the value returned from
signed_serialize. If the value cannot be deserialized for any reason, aValueErrorexception will be raised.This function is useful for deserializing a signed cookie value created by
signed_serialize. For example:cookieval = request.cookies['signed_cookie'] data = signed_deserialize(cookieval, 'secret')
-
check_csrf_origin(request, trusted_origins=None, raises=True)[source]¶ Check the Origin of the request to see if it is a cross site request or not.
If the value supplied by the Origin or Referer header isn't one of the trusted origins and
raisesisTrue, this function will raise apyramid.exceptions.BadCSRFOriginexception but ifraisesisFalsethis function will returnFalseinstead. If the CSRF origin checks are successful this function will returnTrueunconditionally.Additional trusted origins may be added by passing a list of domain (and ports if nonstandard like ['example.com', 'dev.example.com:8080']) in with the
trusted_originsparameter. Iftrusted_originsisNone(the default) this list of additional domains will be pulled from thepyramid.csrf_trusted_originssetting.Note that this function will do nothing if request.scheme is not https.
New in version 1.7.
-
check_csrf_token(request, token='csrf_token', header='X-CSRF-Token', raises=True)[source]¶ Check the CSRF token in the request's session against the value in
request.POST.get(token)(if a POST request) orrequest.headers.get(header). If atokenkeyword is not supplied to this function, the stringcsrf_tokenwill be used to look up the token inrequest.POST. If aheaderkeyword is not supplied to this function, the stringX-CSRF-Tokenwill be used to look up the token inrequest.headers.If the value supplied by post or by header doesn't match the value supplied by
request.session.get_csrf_token(), andraisesisTrue, this function will raise anpyramid.exceptions.BadCSRFTokenexception. If the values differ andraisesisFalse, this function will returnFalse. If the CSRF check is successful, this function will returnTrueunconditionally.Note that using this function requires that a session factory is configured.
See Checking CSRF Tokens Automatically for information about how to secure your application automatically against CSRF attacks.
New in version 1.4a2.
Changed in version 1.7a1: A CSRF token passed in the query string of the request is no longer considered valid. It must be passed in either the request body or a header.
-
SignedCookieSessionFactory(secret, cookie_name='session', max_age=None, path='/', domain=None, secure=False, httponly=False, set_on_exception=True, timeout=1200, reissue_time=0, hashalg='sha512', salt='pyramid.session.', serializer=None)[source]¶ New in version 1.5.
Configure a session factory which will provide signed cookie-based sessions. The return value of this function is a session factory, which may be provided as the
session_factoryargument of apyramid.config.Configuratorconstructor, or used as thesession_factoryargument of thepyramid.config.Configurator.set_session_factory()method.The session factory returned by this function will create sessions which are limited to storing fewer than 4000 bytes of data (as the payload must fit into a single cookie).
Parameters:
secret- A string which is used to sign the cookie. The secret should be at
least as long as the block size of the selected hash algorithm. For
sha512this would mean a 128 bit (64 character) secret. It should be unique within the set of secret values provided to Pyramid for its various subsystems (see Admonishment Against Secret-Sharing). hashalg- The HMAC digest algorithm to use for signing. The algorithm must be
supported by the
hashliblibrary. Default:'sha512'. salt- A namespace to avoid collisions between different uses of a shared
secret. Reusing a secret for different parts of an application is
strongly discouraged (see Admonishment Against Secret-Sharing).
Default:
'pyramid.session.'. cookie_name- The name of the cookie used for sessioning. Default:
'session'. max_age- The maximum age of the cookie used for sessioning (in seconds).
Default:
None(browser scope). path- The path used for the session cookie. Default:
'/'. domain- The domain used for the session cookie. Default:
None(no domain). secure- The 'secure' flag of the session cookie. Default:
False. httponly- Hide the cookie from Javascript by setting the 'HttpOnly' flag of the
session cookie. Default:
False. timeout- A number of seconds of inactivity before a session times out. If
Nonethen the cookie never expires. This lifetime only applies to the value within the cookie. Meaning that if the cookie expires due to a lowermax_age, then this setting has no effect. Default:1200. reissue_timeThe number of seconds that must pass before the cookie is automatically reissued as the result of accessing the session. The duration is measured as the number of seconds since the last session cookie was issued and 'now'. If this value is
0, a new cookie will be reissued on every request accessing the session. IfNonethen the cookie's lifetime will never be extended.A good rule of thumb: if you want auto-expired cookies based on inactivity: set the
timeoutvalue to 1200 (20 mins) and set thereissue_timevalue to perhaps a tenth of thetimeoutvalue (120 or 2 mins). It's nonsensical to set thetimeoutvalue lower than thereissue_timevalue, as the ticket will never be reissued. However, such a configuration is not explicitly prevented.Default:
0.set_on_exception- If
True, set a session cookie even if an exception occurs while rendering a view. Default:True. serializer- An object with two methods:
loadsanddumps. Theloadsmethod should accept bytes and return a Python object. Thedumpsmethod should accept a Python object and return bytes. AValueErrorshould be raised for malformed inputs. If a serializer is not passed, thepyramid.session.PickleSerializerserializer will be used.
-
UnencryptedCookieSessionFactoryConfig(secret, timeout=1200, cookie_name='session', cookie_max_age=None, cookie_path='/', cookie_domain=None, cookie_secure=False, cookie_httponly=False, cookie_on_exception=True, signed_serialize=<function signed_serialize>, signed_deserialize=<function signed_deserialize>)[source]¶ Deprecated since version 1.5: Use
pyramid.session.SignedCookieSessionFactory()instead. Caveat: Cookies generated usingSignedCookieSessionFactoryare not compatible with cookies generated usingUnencryptedCookieSessionFactory, so existing user session data will be destroyed if you switch to it.Configure a session factory which will provide unencrypted (but signed) cookie-based sessions. The return value of this function is a session factory, which may be provided as the
session_factoryargument of apyramid.config.Configuratorconstructor, or used as thesession_factoryargument of thepyramid.config.Configurator.set_session_factory()method.The session factory returned by this function will create sessions which are limited to storing fewer than 4000 bytes of data (as the payload must fit into a single cookie).
Parameters:
secret- A string which is used to sign the cookie.
timeout- A number of seconds of inactivity before a session times out.
cookie_name- The name of the cookie used for sessioning.
cookie_max_age- The maximum age of the cookie used for sessioning (in seconds).
Default:
None(browser scope). cookie_path- The path used for the session cookie.
cookie_domain- The domain used for the session cookie. Default:
None(no domain). cookie_secure- The 'secure' flag of the session cookie.
cookie_httponly- The 'httpOnly' flag of the session cookie.
cookie_on_exception- If
True, set a session cookie even if an exception occurs while rendering a view. signed_serialize- A callable which takes more or less arbitrary Python data structure and
a secret and returns a signed serialization in bytes.
Default:
signed_serialize(using pickle). signed_deserialize- A callable which takes a signed and serialized data structure in bytes
and a secret and returns the original data structure if the signature
is valid. Default:
signed_deserialize(using pickle).
-
BaseCookieSessionFactory(serializer, cookie_name='session', max_age=None, path='/', domain=None, secure=False, httponly=False, timeout=1200, reissue_time=0, set_on_exception=True)[source]¶ New in version 1.5.
Configure a session factory which will provide cookie-based sessions. The return value of this function is a session factory, which may be provided as the
session_factoryargument of apyramid.config.Configuratorconstructor, or used as thesession_factoryargument of thepyramid.config.Configurator.set_session_factory()method.The session factory returned by this function will create sessions which are limited to storing fewer than 4000 bytes of data (as the payload must fit into a single cookie).
Parameters:
serializer- An object with two methods:
loadsanddumps. Theloadsmethod should accept bytes and return a Python object. Thedumpsmethod should accept a Python object and return bytes. AValueErrorshould be raised for malformed inputs. cookie_name- The name of the cookie used for sessioning. Default:
'session'. max_age- The maximum age of the cookie used for sessioning (in seconds).
Default:
None(browser scope). path- The path used for the session cookie. Default:
'/'. domain- The domain used for the session cookie. Default:
None(no domain). secure- The 'secure' flag of the session cookie. Default:
False. httponly- Hide the cookie from Javascript by setting the 'HttpOnly' flag of the
session cookie. Default:
False. timeout- A number of seconds of inactivity before a session times out. If
Nonethen the cookie never expires. This lifetime only applies to the value within the cookie. Meaning that if the cookie expires due to a lowermax_age, then this setting has no effect. Default:1200. reissue_timeThe number of seconds that must pass before the cookie is automatically reissued as the result of a request which accesses the session. The duration is measured as the number of seconds since the last session cookie was issued and 'now'. If this value is
0, a new cookie will be reissued on every request accessing the session. IfNonethen the cookie's lifetime will never be extended.A good rule of thumb: if you want auto-expired cookies based on inactivity: set the
timeoutvalue to 1200 (20 mins) and set thereissue_timevalue to perhaps a tenth of thetimeoutvalue (120 or 2 mins). It's nonsensical to set thetimeoutvalue lower than thereissue_timevalue, as the ticket will never be reissued. However, such a configuration is not explicitly prevented.Default:
0.set_on_exception- If
True, set a session cookie even if an exception occurs while rendering a view. Default:True.