【发布时间】:2015-09-27 15:31:12
【问题描述】:
在 Django 1.8 简单标记中,我需要解析在上下文中找到的 HTTP_REFERER 的路径。我有一段有效的代码,但我想知道是否可以使用 Django 工具实现更优雅的解决方案。
这是我的代码:
from django.core.urlresolvers import resolve, Resolver404
# [...]
@register.simple_tag(takes_context=True)
def simple_tag_example(context):
# The referer is a full path: http://host:port/path/to/referer/
# We only want the path: /path/to/referer/
referer = context.request.META.get('HTTP_REFERER')
if referer is None:
return ''
# Build the string http://host:port/
prefix = '%s://%s' % (context.request.scheme, context.request.get_host())
path = referer.replace(prefix, '')
resolvermatch = resolve(path)
# Do something very interesting with this resolvermatch...
所以我手动构造了字符串'http://sub.domain.tld:port',然后我将它从context.request.META 中找到的HTTP_REFERER 的完整路径中删除。它有效,但对我来说似乎有点不知所措。
我尝试从referer 构建HttpRequest,但没有成功。是否有可以用来轻松从 URL 中提取路径的类或类型?
【问题讨论】:
-
docs.python.org/2/library/urlparse.html#urlparse.urlunparse 可能有用,但艾哈迈德的回答是最好的。