开发者

Hooking into django views

开发者 https://www.devze.com 2022-12-17 11:53 出处:网络
Simple question. I have bunch of django views. Is there a way to tell django that for each view, use foo(view) instead? Example:

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 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.


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')]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号