本文整理匯總了Python中django.core.exceptions.DisallowedHost方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.DisallowedHost方法的具體用法?Python exceptions.DisallowedHost怎麽用?Python exceptions.DisallowedHost使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.core.exceptions
的用法示例。
在下文中一共展示了exceptions.DisallowedHost方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_host
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def get_host(self):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# There is no hostname validation when DEBUG=True
if settings.DEBUG:
return host
domain, port = split_domain_port(host)
if domain and validate_host(domain, settings.ALLOWED_HOSTS):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg)
示例2: test_host_validation_in_debug_mode
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def test_host_validation_in_debug_mode(self):
"""
If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
allowed.
"""
valid_hosts = ['localhost', '127.0.0.1', '[::1]']
for host in valid_hosts:
request = HttpRequest()
request.META = {'HTTP_HOST': host}
self.assertEqual(request.get_host(), host)
# Other hostnames raise a DisallowedHost.
with self.assertRaises(DisallowedHost):
request = HttpRequest()
request.META = {'HTTP_HOST': 'example.com'}
request.get_host()
示例3: get_host
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def get_host(self):
"""Returns the HTTP host using the environment or request headers."""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = str(self.META['SERVER_PORT'])
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
# There is no hostname validation when DEBUG=True
if settings.DEBUG:
return host
domain, port = split_domain_port(host)
if domain and validate_host(domain, settings.ALLOWED_HOSTS):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg)
示例4: process_response
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def process_response(self, request, response):
try:
self._write_log(request, response, getattr(request, 'saved_body', ''))
except DisallowedHost:
return HttpResponseForbidden()
return response
示例5: process_response
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
if getattr(response, "asynchronous", False):
# This special Tornado "asynchronous" response is
# discarded after going through this code path as Tornado
# intends to block, so we stop here to avoid unnecessary work.
return response
try:
request.get_host()
except DisallowedHost:
# If we get a DisallowedHost exception trying to access
# the host, (1) the request is failed anyway and so the
# below code will do nothing, and (2) the below will
# trigger a recursive exception, breaking things, so we
# just return here.
return response
if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and
not request.path.startswith("/json/")):
subdomain = get_subdomain(request)
if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
try:
get_realm(subdomain)
except Realm.DoesNotExist:
return render(request, "zerver/invalid_realm.html", status=404)
return response
示例6: test_get_host_suggestion_of_allowed_host
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def test_get_host_suggestion_of_allowed_host(self):
"""get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS."""
msg_invalid_host = "Invalid HTTP_HOST header: %r."
msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS."
msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035"
for host in [ # Valid-looking hosts
'example.com',
'12.34.56.78',
'[2001:19f0:feee::dead:beef:cafe]',
'xn--4ca9at.com', # Punycode for öäü.com
]:
request = HttpRequest()
request.META = {'HTTP_HOST': host}
with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, host)):
request.get_host()
for domain, port in [ # Valid-looking hosts with a port number
('example.com', 80),
('12.34.56.78', 443),
('[2001:19f0:feee::dead:beef:cafe]', 8080),
]:
host = '%s:%s' % (domain, port)
request = HttpRequest()
request.META = {'HTTP_HOST': host}
with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, domain)):
request.get_host()
for host in self.poisoned_hosts:
request = HttpRequest()
request.META = {'HTTP_HOST': host}
with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host):
request.get_host()
request = HttpRequest()
request.META = {'HTTP_HOST': "invalid_hostname.com"}
with self.assertRaisesMessage(DisallowedHost, msg_suggestion2 % "invalid_hostname.com"):
request.get_host()
示例7: get_data_from_request
# 需要導入模塊: from django.core import exceptions [as 別名]
# 或者: from django.core.exceptions import DisallowedHost [as 別名]
def get_data_from_request(self, request, event_type):
result = {
"env": dict(get_environ(request.META)),
"method": request.method,
"socket": {"remote_address": request.META.get("REMOTE_ADDR"), "encrypted": request.is_secure()},
"cookies": dict(request.COOKIES),
}
if self.config.capture_headers:
request_headers = dict(get_headers(request.META))
for key, value in request_headers.items():
if isinstance(value, (int, float)):
request_headers[key] = str(value)
result["headers"] = request_headers
if request.method in constants.HTTP_WITH_BODY:
capture_body = self.config.capture_body in ("all", event_type)
if not capture_body:
result["body"] = "[REDACTED]"
else:
content_type = request.META.get("CONTENT_TYPE")
if content_type == "application/x-www-form-urlencoded":
data = compat.multidict_to_dict(request.POST)
elif content_type and content_type.startswith("multipart/form-data"):
data = compat.multidict_to_dict(request.POST)
if request.FILES:
data["_files"] = {field: file.name for field, file in compat.iteritems(request.FILES)}
else:
try:
data = request.body
except Exception as e:
self.logger.debug("Can't capture request body: %s", compat.text_type(e))
data = "<unavailable>"
if data is not None:
result["body"] = data
if hasattr(request, "get_raw_uri"):
# added in Django 1.9
url = request.get_raw_uri()
else:
try:
# Requires host to be in ALLOWED_HOSTS, might throw a
# DisallowedHost exception
url = request.build_absolute_uri()
except DisallowedHost:
# We can't figure out the real URL, so we have to set it to
# DisallowedHost
result["url"] = {"full": "DisallowedHost"}
url = None
if url:
result["url"] = get_url_dict(url)
return result