[英]Python - if, elif, elif, else Statement Not Working as Expected
I'm using Django for a web site and needed to build a context processor to provide referrer (variable named referer
) information. 我正在将Django用于网站,并且需要构建上下文处理器来提供引荐来源(变量为
referer
)信息。
I have a simple if, elif, elif, else statement: 我有一个简单的if,elif,elif,else语句:
[ . . . ]
host = get_current_site(request)
local_url = SITE_URLS['local']
dev_url = SITE_URLS['dev']
prod_url = SITE_URLS['prod']
# print referer for debugging purposes - remove when done...
print("current host: {0}".format(host))
print("current urls: {0} {1} {2}".format(local_url, dev_url, prod_url))
# determine default referer - eg, set as host/site name
if host == prod_url:
referer = prod_url
elif host == dev_url:
referer = dev_url
elif host == local_url:
referer = local_url
else:
# set referer for current request
try:
referer = request.META['HTTP_REFERER']
except KeyError as e:
print('ERROR: key error - referer doesn\'t exist: {0}'.format(str(e)));
[ . . . ]
What's weird is that the print statements above yield the host
being equal to the local_url
(from console): 奇怪的是,上面的打印语句产生的
host
等于local_url
(从控制台):
current host: http://localhost:8000
current urls: http://localhost:8000 [ . . . ]
Yet it is still evaluating the else > try and throwing a key error... The point is that only when the default host/site is not available, then the request.META['HTTP_REFERER']
is valid. 但是它仍在评估else>尝试并抛出关键错误...重点是,仅当默认主机/站点不可用时,
request.META['HTTP_REFERER']
有效。
What is going wrong here? 这是怎么了? I'm missing something.
我想念一些东西。 Python is telling me that
host != local_url
but why? Python告诉我
host != local_url
但是为什么呢?
EDIT 编辑
Thanks to a great hint from @Martijn Pieters. 感谢@Martijn Pieters的一个很好的提示。 I changed the print statements and now see this:
我更改了打印语句,现在看到了:
current host: <Site: http://localhost:8000>
current urls: 'http://localhost:8000'
I think I forgot to use the attributes for the sites framework: 我想我忘了使用网站框架的属性:
https://docs.djangoproject.com/en/dev/ref/contrib/sites/ https://docs.djangoproject.com/en/dev/ref/contrib/sites/
Most likely you have a whitespace issue; 您很可能遇到空白问题; replace your formatting with:
将格式替换为:
print("current host: {0!r}".format(host))
print("current urls: {0!r} {1!r} {2!r}".format(local_url, dev_url, prod_url))
to use repr()
values instead; 改用
repr()
值; these will include more information on the type of the value and any trailing whitespace will be immediately obvious. 这些将包含有关值类型的更多信息,任何尾随空格将立即显而易见。
If you see a django.contrib.sites.models.Site
object, compare against the domain
attribute: 如果看到
django.contrib.sites.models.Site
对象,请与domain
属性进行比较:
if host.domain == prod_url:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.