从此片段中,您可以创建自定义装饰器
from functools import wraps
from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect
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
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
您可以通过以下方式使用其中任何一种:
@redirect('http://stackoverflow.com')
def myview(response):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('my_template.html', file_object=resp)
return result
或者:
@permanent_redirect('http://stackoverflow.com')
def myview(response):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('my_template.html', file_object=resp)
return result