重定向前添加请求头 [英] Add request header before redirection

查看:4539
本文介绍了重定向前添加请求头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个新的客户端改装Django网络应用程序。为此,我添加了一个url模式,将请求从新客户端重定向到旧的URL模式。



from: -

 (('api /(?P< ; phone> \w +)/ MessageA',handle_a_message)
('api /(?P< phone> \w +)/ MessageB',handle_b_message),
...)

to: -

 (('api /(?P< phone> \w +)/ MessageA',handle_a_message),
('api /(?P< phone> \w +)/ MessageB',handle_b_message)
('api / newclient',handle_newclient)
...)

view.handle_newclient

  def handle_newclient(request):
return redirect('/ api /%(phone) %(msg)s'%request.GET)

这有点工作。然而,新客户端并没有做这些url需要的基本认证。另外默认输出是json,新客户端需要纯文本。有没有办法在重定向到现有网址之前调整标题?

解决方案

Django FBV应该返回HTTPResponse对象其子类)。 Django shorcut redirect返回HttpResponseRedirect,它是HTTPResponse的一个子类。这意味着我们可以设置 redirect()的标题,我们将为典型的HTTPResponse对象设置标题。我们可以这样做:

  def my_view(request):
response = redirect('http://
#设置'测试'头,然后删除
响应['测试'] ='测试'
del响应['测试']
#设置'测试头'头
响应['测试头'] ='测试头'
返回响应

相关文档 here 此处


I am retrofitting a Django web app for a new client. To this end I have added a url pattern that redirects requests from new client to old url patterns.

from:-

(('api/(?P<phone>\w+)/MessageA', handle_a_message),
 ('api/(?P<phone>\w+)/MessageB', handle_b_message),
  ...)

to:-

(('api/(?P<phone>\w+)/MessageA', handle_a_message),
 ('api/(?P<phone>\w+)/MessageB', handle_b_message),
 ('api/newclient', handle_newclient)
  ...)

views.handle_newclient

def handle_newclient(request):
    return redirect('/api/%(phone)s/%(msg)s' % request.GET)

This somewhat works. However the new client doesn't do basic auth which those url's need. Also the default output is json where the new client needs plain text. Is there a way I can tweak the headers before redirecting to the existing url's?

解决方案

Django FBV's should return an HTTPResponse object (or subclass thereof). The Django shorcut redirect returns HttpResponseRedirect which is a subclass of HTTPResponse. This means we can set the headers for redirect() the way we will set headers for a typical HTTPResponse object. We can do that like so:

def my_view(request):
    response = redirect('http://www.gamefaqs.com')
    # Set 'Test' header and then delete
    response['Test'] = 'Test'
    del response['Test']
    # Set 'Test Header' header
    response['Test Header'] = 'Test Header'
    return response

Relevant docs here and here.

这篇关于重定向前添加请求头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆