【问题标题】:Django : extract a path from a full URLDjango:从完整的 URL 中提取路径
【发布时间】:2015-09-27 15:31:12
【问题描述】:

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

【问题讨论】:

标签: python django url


【解决方案1】:

你可以使用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'

【讨论】:

  • 注:在python 2中,相关模块为urlparse:docs.python.org/2/library/urlparse.html
  • 我为什么要查看 Django 模块?当然,Python 已经为此提供了一个。非常感谢你。我需要睡觉;)
  • python3: import urllib urllib.parse.urlparse('urlhere')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 2012-07-26
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多