2015-09-27 84 views
0

在Django 1.8简单标记中,我需要解析上下文中找到的HTTP_REFERER的路径。我有一段可行的代码,但我想知道是否可以使用Django工具实现更优雅的解决方案。Django:从完整的URL中提取路径

这里是我的代码:

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中轻松提取路径的类或类型?

+0

https://docs.python.org/2/library/urlparse.html#urlparse.urlunparse可能是有用的,但艾哈迈德的回答是最好的。 –

回答

5

您可以使用urlparse模块提取路径:

>>> import urlparse 
>>> parsed = urlparse.urlparse('http://stackoverflow.com/questions/32809595') 
>>> parsed.path 
'/questions/32809595' 
+1

注意:在Python 2中,相关模块是'urlparse':https://docs.python.org/2/library/urlparse.html –

+0

为什么我在Django模块中查找?当然,Python已经有了一个。非常感谢你。我需要睡觉;) – Antwane

+0

@CoreyGoldberg我编辑了答案,谢谢。 – ahmed