1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 | from functools import wraps
from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect
def permanent_redirect(url):
"""
Executes a HTTP 301 (permanent) redirect after the view finishes processing. If a
value is returned, it is ignored. Allows for the view url to be callable so the
reverse() lookup can be used.
@permanent_redirect('/another-url/')
def redirect_view(request):
...
@redirect(lambda: reverse('some_viewname'))
def do_redirect(request):
...
"""
def outer(f):
@wraps(f)
def inner(request, *args, **kwargs):
f(request, *args, **kwargs)
return HttpResponsePermanentRedirect(url if not callable(url) else url())
return inner
return outer
def redirect(url):
"""
Executes a HTTP 302 redirect after the view finishes processing. If a value is
returned, it is ignored. Allows for the view url to be callable so the
reverse() lookup can be used.
@redirect('http://www.google.com/')
def goto_google(request):
pass
@redirect(lambda: reverse('some_viewname'))
def do_redirect(request):
...
"""
def outer(f):
@wraps(f)
def inner(request, *args, **kwargs):
f(request, *args, **kwargs)
return HttpResponseRedirect(url if not callable(url) else url())
return inner
return outer
|
Comments
Why dont you use django.views.generic.simple.redirect_to view?
#
These decorators are supplemental to the generic django views. They allow you to process any number of items before the redirection.
#
Yes, but what is a difference between:
def view1(request): do_actions redirect_to(...)
and
@redirect(...) def view2(request): do_actions
I don't know what others think about it, but for me this snippet doesn't contain 'value added'.
#