在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...
Run Code Online (Sandbox Code Playgroud)
所以我手动构造字符串' http://sub.domain.tld:port ',然后将其从完整路径中删除到HTTP_REFERER中找到context.request.META.它有效,但对我来说似乎有点压倒性.
我试图建立一个HttpRequest从referer没有成功.是否有可用于轻松从URL中提取路径的类或类型?
您可以使用urlparse模块提取路径:
>>> import urlparse
>>> parsed = urlparse.urlparse('http://stackoverflow.com/questions/32809595')
>>> parsed.path
'/questions/32809595'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1218 次 |
| 最近记录: |