django is_safe_url方法使用说明

is_safe_url() 对其进行验证。文档字符串很好地解释了它的用法:

is_safe_url(url, host=None, allowed_hosts=None, require_https=False) 如果url是安全重定向(即不会指向其他主机并使用安全方案),则返回True。空 url 总是返回 False。如果 require_https 为 True(默认为 False),则只有 https 被视为有效方案。

我们来看一些例子。

相对URL被认为是安全的:

>>> # Import the function first.
>>> from django.utils.http import is_safe_url
>>> is_safe_url('/profile/')
True

通常认为指向其他主机的URL不安全:

>>> is_safe_url('https://myawesomedjangowebapp.com/profile/')
False

如果在 ALLOWED_HOSTS中 提供了指向另一个主机的URL,则该URL被认为是安全的:

>>> is_safe_url('https://myawesomedjangowebapp.com/profile/',
...             allowed_hosts={'myawesomedjangowebapp.com'})
True

如果参数 require_https 为True,则使用 http 方案的URL被视为不安全:

>>> is_safe_url('http://myawesomedjangowebapp.com/profile/',
...             allowed_hosts={'myawesomedjangowebapp.com'},
...             require_https=True)
False

原文:https://zhuanlan.zhihu.com/p/52253513

原文地址:https://www.cnblogs.com/Fmaj7/p/13750227.html