Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top