Django:从完整的URL中提取路径

3
在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中提取路径?

https://docs.python.org/2/library/urlparse.html#urlparse.urlunparse 可能会有用,但是Ahmed的答案是最好的。 - Corey Goldberg
1个回答

10
你可以使用 urlparse 模块来提取路径:
try:
    from urllib.parse import urlparse  # Python 3 
except ImportError:
    from urlparse import urlparse  # Python 2

parsed = urlparse('https://dev59.com/7I_ea4cB1Zd3GeqPPYfo')
print(parsed.path)

输出:

'/questions/32809595'

1
注意:在Python 2中,相关模块是urlparse:https://docs.python.org/2/library/urlparse.html - Corey Goldberg
我为什么要查看Django模块?当然,Python已经有一个这样的模块了。非常感谢。我需要睡觉了 ;) - Antwane
2
python3Ôºö import urllib urllib.parse.urlparse('urlhere') - 55651909-089b-4e04-9408-47c5bf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接