

Using a Request Factory in Pyramid to write a little less code - brianr
http://ratchet.io/blog/post/2012/09/07/using-pyramid-request-factory-to-write-less-code/

======
SoftwareMaven
We did the same thing to put our authenticated user on the request object, but
I still didn't like passing the request around everywhere, so eventually I
made some middleware that attached the request as a threadlocal variable, so
clients could just refer to the variable if they needed it.

The caveat, of course, is that if you are using anything other than a vanilla
CGI-type gateway, you need to make sure to clear out the threadlocal variable
at the end of the request. Don't want it getting reused by somebody else. :)

~~~
brianr
What did you attach the request to? Pyramid _does_ provide a way to get the
current request:

    
    
        pyramid.threadlocal.get_current_request()

~~~
SoftwareMaven
I created my own variable, which I did for two reasons:

First, I didn't want dependencies on Pyramid imports in certain sections of my
code.

Second, this comment in the Pyramid docs: _This function should be used
extremely sparingly, usually only in unit testing code. it’s almost always
usually a mistake to use get_current_request outside a testing context because
its usage makes it possible to write code that can be neither easily tested
nor scripted._

That made me think that they might not have done the due diligence in making
sure that my code was safe (which is completely reasonable since they made it
explicitly clear _they_ felt that way). Since I knew exactly how I was
deploying, I could make it safe.

------
zimbatm
I'm not a fluent pythonist, but wouldn't you achieve the same result by
renaming your "request" argument to "self" ?

Before: > def flash_success(request, body, title=''): >
request.session.flash({'body': body, 'title': title'})

After: > def flash_success(self, body, title=''): >
self.session.flash({'body': body, 'title': title'})

~~~
__del__
I believe the point was to unify request.session.flash(…) with things like
helpers.flash_success(request,…) such that both flash and flash_success _can_
be methods on the request object.

~~~
brianr
Yep, this is correct.

------
arnarbi
See the disqus comment on set_request_property as well.

------
kookiekrak
very cool!

