本文整理汇总了Python中django.http.HttpRequest.get_host方法的典型用法代码示例。如果您正苦于以下问题:Python HttpRequest.get_host方法的具体用法?Python HttpRequest.get_host怎么用?Python HttpRequest.get_host使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.HttpRequest
的用法示例。
在下文中一共展示了HttpRequest.get_host方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reports
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def reports(request):
context = {}
if request.method == 'GET':
try:
reports = ReportModel.objects.all().order_by('week_ending')
for report in reports:
d = datetime.strptime(
str(report.week_ending), "%Y-%m-%d")
report.time_title = "Week ending {}".format(
d.strftime('%B %-d, %Y'))
context['reports'] = reports
context['meta_description'] = params.meta_descriptions['reports']
context['page'] = 'reports'
context['sUri'] = 'http://{}'.format(HttpRequest.get_host(request))
response = render(request, 'news/stearsreport.html', context)
icache = 'infinitecache:{}'.format('reports')
cache.set(icache, response, 60*60*24*14)
return response
except Exception:
response = cache.get(icache, None)
return response
context['sUri'] = 'http://{}'.format(HttpRequest.get_host(request))
response = render(request, 'news/stearsreport.html', context)
return response
示例2: check
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def check(request: HttpRequest):
s_h = settings.SECURE_PROXY_SSL_HEADER
a_h = settings.DF_REMOTE_USER_HEADER
# noinspection PyArgumentList
gpg_valid = False
for key in GPG.list_keys(False):
if key['keyid'] == settings.GNUPG_KEYID:
gpg_valid = True
user = request.user
template_values = {
'media_root': settings.MEDIA_ROOT, 'media_url': settings.MEDIA_URL,
'static_root': settings.STATIC_ROOT, 'static_url': settings.STATIC_URL,
'debug': settings.DEBUG, 'use_x_forwared_host': settings.USE_X_FORWARDED_HOST,
'secure_proxy_ssl_header_name': s_h[0][5:],
'secure_proxy_ssl_header_value': s_h[1],
'authentication_header': a_h,
'has_authentication_header': request.META.get(a_h, '') == user.username,
'has_secure_proxy_ssl_header': request.META.get(s_h[0], '') == s_h[1],
'host': request.get_host().rpartition(':')[0],
'has_allowed_host': request.get_host() in settings.ALLOWED_HOSTS,
'gpg_valid': gpg_valid, 'gpg_available': GPG.list_keys(False),
}
return TemplateResponse(request, 'moneta/help.html', template_values)
示例3: check
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def check(request: HttpRequest):
s_h = settings.SECURE_PROXY_SSL_HEADER
a_h = settings.FLOOR_AUTHENTICATION_HEADER
# noinspection PyArgumentList
gpg_valid = False
for key in GPG.list_keys(False):
if key['keyid'] == settings.GNUPG_KEYID:
gpg_valid = True
import moneta.defaults
default_conf_path = moneta.defaults.__file__
if default_conf_path.endswith('.pyc'):
default_conf_path = default_conf_path[:-1]
template_values = {
'media_root': settings.MEDIA_ROOT, 'media_url': settings.MEDIA_URL,
'static_root': settings.STATIC_ROOT, 'static_url': settings.STATIC_URL,
'debug': settings.DEBUG, 'use_x_forwared_host': settings.USE_X_FORWARDED_HOST,
'secure_proxy_ssl_header_name': s_h[0][5:],
'secure_proxy_ssl_header_value': s_h[1],
'authentication_header': a_h,
'has_authentication_header': request.META.get(a_h, '') == request.user.username,
'has_secure_proxy_ssl_header': request.META.get(s_h[0], '') == s_h[1],
'host': request.get_host().rpartition(':')[0],
'has_allowed_host': request.get_host() in settings.ALLOWED_HOSTS,
'gpg_valid': gpg_valid, 'gpg_available': GPG.list_keys(False),
}
return render_to_response('moneta/help.html', template_values, RequestContext(request))
示例4: process_response
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
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:
realm = get_realm(subdomain)
if (realm is None):
return render(request, "zerver/invalid_realm.html")
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie.
"""
try:
accessed = request.session.accessed
modified = request.session.modified
except AttributeError:
pass
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
# Skip session save for 500 responses, refs #3881.
if response.status_code != 500:
request.session.save()
host = request.get_host().split(':')[0]
# The subdomains feature overrides the
# SESSION_COOKIE_DOMAIN setting, since the setting
# is a fixed value and with subdomains enabled,
# the session cookie domain has to vary with the
# subdomain.
session_cookie_domain = host
response.set_cookie(settings.SESSION_COOKIE_NAME,
request.session.session_key, max_age=max_age,
expires=expires, domain=session_cookie_domain,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None)
return response
示例5: test_host_validation_disabled_in_debug_mode
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def test_host_validation_disabled_in_debug_mode(self):
"""If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
request = HttpRequest()
request.META = {"HTTP_HOST": "example.com"}
self.assertEqual(request.get_host(), "example.com")
# Invalid hostnames would normally raise a SuspiciousOperation,
# but we have DEBUG=True, so this check is disabled.
request = HttpRequest()
request.META = {"HTTP_HOST": "invalid_hostname.com"}
self.assertEqual(request.get_host(), "invalid_hostname.com")
示例6: test_http_get_host
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def test_http_get_host(self):
# Check if X_FORWARDED_HOST is provided.
request = HttpRequest()
request.META = {
"HTTP_X_FORWARDED_HOST": "forward.com",
"HTTP_HOST": "example.com",
"SERVER_NAME": "internal.com",
"SERVER_PORT": 80,
}
# X_FORWARDED_HOST is ignored.
self.assertEqual(request.get_host(), "example.com")
# Check if X_FORWARDED_HOST isn't provided.
request = HttpRequest()
request.META = {"HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80}
self.assertEqual(request.get_host(), "example.com")
# Check if HTTP_HOST isn't provided.
request = HttpRequest()
request.META = {"SERVER_NAME": "internal.com", "SERVER_PORT": 80}
self.assertEqual(request.get_host(), "internal.com")
# Check if HTTP_HOST isn't provided, and we're on a nonstandard port
request = HttpRequest()
request.META = {"SERVER_NAME": "internal.com", "SERVER_PORT": 8042}
self.assertEqual(request.get_host(), "internal.com:8042")
# Poisoned host headers are rejected as suspicious
legit_hosts = [
"example.com",
"example.com:80",
"12.34.56.78",
"12.34.56.78:443",
"[2001:19f0:feee::dead:beef:cafe]",
"[2001:19f0:feee::dead:beef:cafe]:8080",
"xn--4ca9at.com", # Punnycode for öäü.com
"anything.multitenant.com",
"multitenant.com",
"insensitive.com",
]
poisoned_hosts = [
"[email protected]",
"example.com:[email protected]",
"example.com:[email protected]:80",
"example.com:80/badpath",
"example.com: recovermypassword.com",
"other.com", # not in ALLOWED_HOSTS
]
for host in legit_hosts:
request = HttpRequest()
request.META = {"HTTP_HOST": host}
request.get_host()
for host in poisoned_hosts:
with self.assertRaises(SuspiciousOperation):
request = HttpRequest()
request.META = {"HTTP_HOST": host}
request.get_host()
示例7: getProfile
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def getProfile(request):
"""
required paras:
string username
"""
# problem: picture cannot be encoded in json package
# friends_set not found
if request.DATA.has_key('username'):
username = request.DATA['username']
else:
return FailResWithMsg("username not found")
try:
user = User.objects.get(username = username)
except User.DoesNotExist:
return FailResWithMsg("User not exists")
allposts = user.posts_set.all()
jdata = [{
'username' : username,
'photo' : '/'.join([HttpRequest.get_host(request), user.myuserinfo.photo.url]),
# 'numOfFriends' : user.friends_set.count(),
'numOfFavRests' : user.favrestaurants_set.count(),
'numOfFavDishes' : user.favdishes_set.count(),
'numOfChickIn' : user.checkins_set.count(),
'numOfUsertags' : user.usertags_set.count(),
'numOfReviews' : user.reviews_set.count(),
'numOfLikes' : user.likes_set.count(),
'numOfTries' : user.tries_set.count(),
}]
return SuccessRes(data = jdata)
示例8: _redirect
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def _redirect(self, request, secure):
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol, HttpRequest.get_host(request), request.get_full_path())
if settings.DEBUG and request.method == 'POST':
raise RuntimeError, """Django can't perform a SSL redirect while maintaining POST data. Please structure your views so that redirects only occur during GETs."""
return HttpResponsePermanentRedirect(newurl)
示例9: test_host_validation_disabled_in_debug_mode
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def test_host_validation_disabled_in_debug_mode(self):
"""If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
request = HttpRequest()
request.META = {
'HTTP_HOST': 'example.com',
}
self.assertEqual(request.get_host(), 'example.com')
示例10: report_error
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def report_error(request: HttpRequest, user_profile: UserProfile, message: str=REQ(),
stacktrace: str=REQ(), ui_message: bool=REQ(validator=check_bool),
user_agent: str=REQ(), href: str=REQ(), log: str=REQ(),
more_info: Optional[Dict[str, Any]]=REQ(validator=check_dict([]), default=None)
) -> HttpResponse:
"""Accepts an error report and stores in a queue for processing. The
actual error reports are later handled by do_report_error (below)"""
if not settings.BROWSER_ERROR_REPORTING:
return json_success()
if more_info is None:
more_info = {}
js_source_map = get_js_source_map()
if js_source_map:
stacktrace = js_source_map.annotate_stacktrace(stacktrace)
try:
version = subprocess.check_output(["git", "log", "HEAD^..HEAD", "--oneline"],
universal_newlines=True) # type: Optional[str]
except Exception:
version = None
# Get the IP address of the request
remote_ip = request.META.get('HTTP_X_REAL_IP')
if remote_ip is None:
remote_ip = request.META['REMOTE_ADDR']
# For the privacy of our users, we remove any actual text content
# in draft_content (from drafts rendering exceptions). See the
# comment on privacy_clean_markdown for more details.
if more_info.get('draft_content'):
more_info['draft_content'] = privacy_clean_markdown(more_info['draft_content'])
if user_profile.is_authenticated:
email = user_profile.delivery_email
full_name = user_profile.full_name
else:
email = "[email protected]"
full_name = "Anonymous User"
queue_json_publish('error_reports', dict(
type = "browser",
report = dict(
host = request.get_host().split(":")[0],
ip_address = remote_ip,
user_email = email,
user_full_name = full_name,
user_visible = ui_message,
server_path = settings.DEPLOY_ROOT,
version = version,
user_agent = user_agent,
href = href,
message = message,
stacktrace = stacktrace,
log = log,
more_info = more_info,
)
))
return json_success()
示例11: sendPasswordResetEmail
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def sendPasswordResetEmail(request):
email = request.POST.get('email', '')
user=User.objects.filter(email=email).first()
result = False
if user is not None:
subject = "Password Zurücksetzen book²"
confirmId = get_random_string(length=32)
entry = PasswordReset.objects.filter(user=user).first()
# create entry if not exists
if entry is None:
entry = PasswordReset()
# add/edit entry
entry.uuid = confirmId
entry.user = user
entry.save()
link = 'https://' + HttpRequest.get_host(request) + reverse('app_user:new_password', kwargs={'uuid': confirmId})
message = 'Hallo '+ user.first_name + ' ' + user.last_name + ',<br><br> um Ihr Passwort zurückzusetzen, klicken Sie bitte auf den Link: <a href="' + link + '">Bestätigen</a><br>Sollten Sie den Link nicht nutzen könnten dann kopieren Sie bitte folgende URL in Ihren Browser:<br> ' + link + '<br><br>Ihr book² team'
msg = EmailMessage(subject, message, [], [email])
msg.content_subtype = "html"
result = msg.send()
return result
示例12: test_host_validation_in_debug_mode
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [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()
示例13: get_subdomain
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def get_subdomain(request: HttpRequest) -> Text:
# The HTTP spec allows, but doesn't require, a client to omit the
# port in the `Host` header if it's "the default port for the
# service requested", i.e. typically either 443 or 80; and
# whatever Django gets there, or from proxies reporting that via
# X-Forwarded-Host, it passes right through the same way. So our
# logic is a bit complicated to allow for that variation.
#
# For both EXTERNAL_HOST and REALM_HOSTS, we take a missing port
# to mean that any port should be accepted in Host. It's not
# totally clear that's the right behavior, but it keeps
# compatibility with older versions of Zulip, so that's a start.
host = request.get_host().lower()
m = re.search('\.%s(:\d+)?$' % (settings.EXTERNAL_HOST,),
host)
if m:
subdomain = host[:m.start()]
if subdomain in settings.ROOT_SUBDOMAIN_ALIASES:
return Realm.SUBDOMAIN_FOR_ROOT_DOMAIN
return subdomain
for subdomain, realm_host in settings.REALM_HOSTS.items():
if re.search('^%s(:\d+)?$' % (realm_host,),
host):
return subdomain
return Realm.SUBDOMAIN_FOR_ROOT_DOMAIN
示例14: _redirect
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def _redirect(self, request, secure):
protocol = secure and 'https' or 'http'
newurl = '%s://%s%s' % (protocol, HttpRequest.get_host(request), request.get_full_path())
if settings.DEBUG and request.method == 'POST':
raise RuntimeError("Django can't perform a SSL redirect while maintaining POST data. Please restructure your views so that redirects only occur during GETS.")
示例15: business
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import get_host [as 别名]
def business(request, sector):
cache_name = 'newscache:{}{}'.format('business', sector)
icache = 'infinitecache:{}{}'.format('business', sector)
response = cache.get(cache_name, None)
if response:
return response
context = {}
absolute_url = 'http://{}'.format(HttpRequest.get_host(request))
if request.method == 'GET':
try:
onsite = mongo_calls('onsite')
context = onsite.find_one({'page': 'b_e', 'sector': sector})
context['sUri'] = absolute_url
context['meta_description'] = params.meta_descriptions['b_e'][sector]
response = render(request, 'news/business.html', context)
cache.set(cache_name, response, 60*60*24)
cache.set(icache, response, 60*60*24*14)
return response
except Exception:
# Log exception
response = cache.get(icache, None)
return response
context['sUri'] = absolute_url
response = render(request, 'news/business.html', context)
return response