librelist archives

« back to archive

Attach the current view to the request

Attach the current view to the request

From:
Dan Jacob
Date:
2010-05-20 @ 10:13
Would it be possible for convenience to attach the current view
function to the request object, in the same fashion as view args, e.g
in dispatch_request():

f = self.view_functions[req.endpoint](**req.view_args)
req.view_func = f
return f

This would provide a useful handle when writing before/after request functions.

Re: [flask] Attach the current view to the request

From:
Armin Ronacher
Date:
2010-05-20 @ 10:16
Hi,

On 5/20/10 12:13 PM, Dan Jacob wrote:
> Would it be possible for convenience to attach the current view
> function to the request object, in the same fashion as view args, e.g
> in dispatch_request():
For comparing views I strongly recommend the string endpoint and 
invoking view functions from before handlers is a bit weird.  Why do you 
want to invoke the function?  Not saying that could not be added, but 
right now I fail to see why this shortcut is useful :)


Regards,
Armin

Re: [flask] Attach the current view to the request

From:
Dan Jacob
Date:
2010-05-20 @ 10:25
Easier to illustrate by example.

Suppose you have a site where, by default, all views require
authentication. You might have something like this:

@before_request
def auth():
    g.user is None
    if 'user_id' in session:
        g.user = User.query.get(session['user_id'])
    if g.user is None:
        return redirect(url_for("login"))

This is obviously easier than having dozens of @login_required
decorators everywhere, as it's the general rule.

However what about your login/signup/forgot password and other views ?
You might want to use a decorator, or just add an attribute to the
view:

def login():
    ....
login._login_required = False

Now in your original before_request decorator you can do this:

@before_request
def auth():
    ....
    if g.user is None and getattr(request.view_func, "_login_required", True):
          return redirect(url_for("login"))

So by having a convenient handle to your view you can handle exceptional cases.

On 20 May 2010 11:16, Armin Ronacher <armin.ronacher@active-4.com> wrote:
> Hi,
>
> On 5/20/10 12:13 PM, Dan Jacob wrote:
>> Would it be possible for convenience to attach the current view
>> function to the request object, in the same fashion as view args, e.g
>> in dispatch_request():
> For comparing views I strongly recommend the string endpoint and
> invoking view functions from before handlers is a bit weird.  Why do you
> want to invoke the function?  Not saying that could not be added, but
> right now I fail to see why this shortcut is useful :)
>
>
> Regards,
> Armin
>