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

Ant*_*ane 0 python django url

在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.它有效,但对我来说似乎有点压倒性.

我试图建立一个HttpRequestreferer没有成功.是否有可用于轻松从URL中提取路径的类或类型?

ahm*_*med 6

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

>>> import urlparse
>>> parsed = urlparse.urlparse('http://stackoverflow.com/questions/32809595')
>>> parsed.path
'/questions/32809595'
Run Code Online (Sandbox Code Playgroud)

  • python3:`import urllib``urllib.parse.urlparse('urlhere')` (2认同)