【问题标题】:How to construct a full URL in django如何在 django 中构建完整的 URL
【发布时间】:2012-11-11 05:08:32
【问题描述】:

我需要让 django 发送一封包含这样 URL 的电子邮件

http://www.mysite.org/history/

“历史”的获取方式如下:

history_url = urlresolvers.reverse('satchmo_order_history')

history_url 是我传递给发送电子邮件的函数的参数,它正确地生成“/history/”。但是我如何获得第一部分? (http://www.mysite.org)

编辑 1

这样做有什么不妥或不便之处吗? :

history = urlresolvers.reverse('satchmo_order_history')
domain = Site.objects.get_current().domain
history_url = 'http://' + domain + history

【问题讨论】:

    标签: django url satchmo


    【解决方案1】:

    如果您有权访问HttpRequest 实例,则可以使用HttpRequest.build_absolute_uri(location)

    absolute_uri = request.build_absolute_uri(relative_uri)
    

    或者,您可以使用sites framework

    import urlparse
    from django.contrib.sites.models import Site
    
    domain = Site.objects.get_current().domain
    absolute_uri = urlparse.urljoin('http://{}'.format(domain), relative_uri)
    

    回复:编辑1

    我倾向于使用urlparse.join,因为它在标准库中,从技术上讲,它是最符合 Python 风格的 URI 组合方式,但我认为您的方法也不错。

    【讨论】:

    • foo = urlparse.urljoin('http://', format(domain)) 给出 http:///mysite.org 和 urlparse.urljoin(foo, history) 然后给出 http:// /历史/我在这里错过了什么?还有 format() 在做什么,{} 是做什么用的?
    • @user1294974 您不能使用urlparse.urljoin 加入'http://' 和您的域,因为它们是部分uri 片段并且它不起作用。您必须连接两个字符串。我为此使用str.format{} 是一个占位符),但它需要 Python 2.7。如果它不起作用,您可以尝试使用 'http://{0}.format(domain)' (Python 2.6),或 'http://%s' % domain 甚至 'http://' + domain,就像您已经在做的那样。
    猜你喜欢
    • 2011-04-28
    • 2020-11-12
    • 2020-10-18
    • 1970-01-01
    • 2011-01-21
    • 2022-12-23
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多