Skip to main content
 首页 » 编程设计

python之Django : extract a path from a full URL

2025年05月04日39arxive

在 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'