如何验证HttpResponseRedirect是否是外部站点?

时间:2013-05-20 08:55:54

标签: python django

我正在使用以下中间件代码段:

class AjaxRedirect(object):
    """
    Instead of returning a 302 for AJAX requests, instead we should return a 200 with a location
    to redirect to so jQuery can forward the user as needed.
    """

    def process_response(self, request, response):
        if request.is_ajax():
            if type(response) == HttpResponseRedirect:
                logger.warn(response.__dict__)
                redirect = '%s&ajaxRedirect=1' % response['Location']
                logger.info('Returned AjaxRedirect to %s' % redirect)
                return HttpResponse(
                    json.dumps(
                        {'redirect': redirect},
                        indent=4,
                        sort_keys=False),
                    content_type='application/json; charset=UTF-8');
        return response

但是,如果重定向到外部站点,我想放弃查询字符串参数。鉴于我同时拥有HttpRequestHttpResponseRedirect个实例,是否有可靠的方法来查找此信息?

添加以下检查:

if request.get_host() in redirect or not redirect.startswith('http'):
    redirect = '%s&ajaxRedirect=1' % redirect

1 个答案:

答案 0 :(得分:2)

不确定这是否是最佳选择,但您可以将request.get_host()response['Location'](或django dev版本中的response.url)进行比较。

希望有所帮助。