Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add user request attr recipe

  • Loading branch information...
commit 29f35e81523005a3c30fa83a1dd95d1151891b2b 1 parent 5e3a4a0
@mcdonc mcdonc authored
Showing with 52 additions and 0 deletions.
  1. +51 −0 authentication.rst
  2. +1 −0  index.rst
51 authentication.rst
@@ -0,0 +1,51 @@
+Making A "User Object" Available as a Request Attribute
+This is you: your application wants a "user object". Pyramid is only willing
+to supply you with a user *id* (via
+````). You're allergic to creating a
+simple function that takes a request object and returns a user object from
+your domain model for unspecified, dubious reasons.
+You've tried using a ``NewRequest`` subscriber to attach a user object to the
+request, but the ``NewRequest`` susbcriber is called on every request, even
+ones for static resources, and this bothers you (which it should).
+Use a combination of a custom request factory and the
+``pyramid.configuration.Config.set_request_factory`` method. Here's the
+custom request factory:
+.. code-block:: python
+ :linenos:
+ from pyramid.decorator import reify
+ from pyramid.request import Request
+ from import authenticated_userid
+ class RequestWithUserAttribute(Request):
+ @reify
+ def user(self):
+ # <your database connection, however you get it, the below line
+ # is just an example>
+ dbconn = self.registry.settings['dbconn']
+ userid = authenticated_userid(self)
+ if userid is not None:
+ return dbconn['users'].query({'id':userid)})
+``pyramid.decorator.reify`` is like the built-in Python ``property``
+decorator, but makes sure that "user" turns into a "real" attribute of the
+request after the first call rather than a property, which executes over and
+over for each access.
+Here's how you should use your new request factory in configuration code:
+.. code-block:: python
+ :linenos:
+ config.set_request_factory(RequestWithUserAttribute)
+Then in your view code, you should be able to happily do ``request.user`` to
+obtain the "user object" related to that request. It will return ``None`` if
+there is no user associated with the request. No inappropriate execution of
+``authenticated_userid`` is done (as would be if you used a ``NewRequest``
1  index.rst
@@ -8,6 +8,7 @@ The Pyramid Cookbook presents topical, practical usages of :mod:`Pyramid`.
+ authentication
Please sign in to comment.
Something went wrong with that request. Please try again.