Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

django - Add request header before redirection

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...