繁体   English   中英

Django:从完整 URL 中提取路径

[英]Django : extract a path from a full 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...

因此,我手动构建字符串“ http://sub.domain.tld:port ”,然后将其从context.request.META找到的 HTTP_REFERER 的完整路径中删除。 它有效,但对我来说似乎有点不知所措。

我试图从referer构建一个HttpRequest没有成功。 是否有一个类或类型可以用来轻松地从 URL 中提取路径?

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

try:
    from urllib.parse import urlparse  # Python 3 
except ImportError:
    from urlparse import urlparse  # Python 2

parsed = urlparse('http://stackoverflow.com/questions/32809595')
print(parsed.path)

输出:

'/questions/32809595'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM