views:

54

answers:

2

Simple question. I have bunch of django views. Is there a way to tell django that for each view, use foo(view) instead? Example:

Instead of writing

@foo
@bar
@baz
def view(request):
    # do something

all the time, I'd like to have

def view(request):
    markers = ['some', 'markers']

and hook this into django:

for view in all_the_views_in_my_app:
    view = do_something_based_on_the_marker(view)

I'd like to have this done at server startup time. Any thoughts?

+1  A: 

I don't know why you want to do this. I don't know either why you don't want to use decorators. But you could use this ugly (and likely error prone) hack as a start:

def view(request):
    pass
view.markers = ['some', 'markers']

some other place:

from app import views
[x for x in views.__dict__.values() if hasattr(x,'markers')]
Till Backhaus
If I use decorators, I have to import the decorators in each views.py file in all my apps, and apply them for each view. I'd like one place where I can plant this hook and pre-process each view. Why? Well, only to code less. If actually it would turn out to be less-readable code, then I change my mind. I guess monkey-patching hasn't led to anything good in production environments...
Attila Oláh
+1  A: 

Depending on what you want to do (or achieve), you can write a custom middelware and implement the method process_view (and/or any other method that you need):

process_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response.

Felix Kling
Hmm, I knew about process_view() and custom middlewares, however, I'd like to do this once on server startup, not before every request. However, this does sound like the only possible non-hacky way of doing it. Thanks.
Attila Oláh