Python - if,elif,elif,else语句不按预期工作

时间:2014-08-17 21:06:13

标签: python django if-statement http-referer

我正在使用Django作为网站,需要构建一个上下文处理器来提供referrer(变量名为referer)信息。

我有一个简单的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)));

[ . . . ]

奇怪的是,上面的打印语句使host等于local_url(来自控制台):

current host: http://localhost:8000
current urls: http://localhost:8000 [ . . . ]

然而它仍在评估 else>尝试并抛出一个关键错误...关键是只有当默认主机/网站不可用时,request.META['HTTP_REFERER']才有效。

这里出了什么问题?我错过了什么。 Python告诉我host != local_url,但为什么?

修改

感谢@Martijn Pieters的精彩提示。我更改了打印语句,现在看到了:

current host: <Site: http://localhost:8000>
current urls: 'http://localhost:8000'

我想我忘了使用网站框架的属性:

https://docs.djangoproject.com/en/dev/ref/contrib/sites/

1 个答案:

答案 0 :(得分:4)

很可能你有空白问题;用以下内容替换您的格式:

print("current host: {0!r}".format(host))
print("current urls: {0!r} {1!r} {2!r}".format(local_url, dev_url, prod_url))

改为使用repr()值;这些将包含有关值类型的更多信息,任何尾随空格都将立即显而易见。

如果您看到django.contrib.sites.models.Site对象,请与domain属性进行比较:

if host.domain == prod_url: