Hooking into django views
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:
开发者_JAVA百科 view = do_something_based_on_the_marker(view)
I'd like to have this done at server startup time. Any thoughts?
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 eitherNone
or anHttpResponse
object. If it returnsNone
, Django will continue processing this request, executing any otherprocess_view()
middleware and, then, the appropriate view. If it returns anHttpResponse
object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return thatHttpResponse
. Response middleware is always called on every response.
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')]
精彩评论