python - 如何验证 HttpResponseRedirect 是否指向外部站点?

标签 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

最佳答案

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

希望有帮助。

关于python - 如何验证 HttpResponseRedirect 是否指向外部站点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16645855/

相关文章:

python - 将 matplotlib 动画嵌入到 tkinter 框架中

django - TinyMCE无论如何都没有出现

python - Python 中的 assertEquals 到底是什么?

python - South 在不同的应用程序中遵循什么迁移顺序?

python - beautifulsoup 查找给定文本的 id

python - 使用 f2py 时,fortran 模块中的函数作用域与为 fortran 程序编译时不同?

python - 给定一个二进制字符串,返回位置 000 位于位置 0,001 位于位置 1。在函数中

python - 将服务添加到 SNS 策略

python - 自定义 Django 登录页面不呈现登录表单

python - 如何在 django rest 框架中验证模型?