【问题标题】:Find Host and Port in a Django Application在 Django 应用程序中查找主机和端口
【发布时间】:2014-07-17 16:32:48
【问题描述】:

我正在连接到 Twitter 流 API 并正在设置 OAuth 握手。我需要请求一个令牌并将callback_url 作为参数字典与发布请求一起发送。

我已经在开发 URL (http://localhost:8000/oauth) 中进行了硬编码,但是当我部署时,它会发生变化。我想设置一些可以找到主机和端口并设置引用的东西。理想情况下,看起来像 "http://%s/oauth" % (domain_name)

我试过同时使用 os 和 socket 模块,代码如下:

class OAuth:

    def request_oauthtoken(self):
        name = socket.gethostname()
        ip = socket.gethostbyname(name)
        domain = socket.gethostbyaddr(ip) # Sequence attempts to find the current domain name.  This will add expandability to the calling the API, as opposed to hard coding it in.  It's not returning what I'm expecting


        payload = { 'oauth_callback': 'http://localhost:8000/oauth' }
        print(domain)
        return payload

domain 返回('justins-mbp-2.local.tld', ['145.15.168.192.in-addr.arpa'], ['192.168.15.145'])

name 返回上述元组的第一个元素,ip 返回从集合中展开的元组的最后一项。

我正在寻找localhostlocalhost:8000 的返回值。我可以和任何一个一起工作。

【问题讨论】:

    标签: python django localhost httprequest host


    【解决方案1】:

    调用request.build_absolute_uri(),然后提取域。

    文档:

    HttpRequest.build_absolute_uri(location) 返回绝对URI形式 的位置。如果未提供位置,则位置将设置为 request.get_full_path().

    如果位置已经是绝对 URI,则不会更改。 否则使用服务器变量构建绝对 URI 在此请求中可用。

    示例:“http://example.com/music/bands/the_beatles/?print=true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 2011-08-01
      • 2019-09-25
      • 2019-08-19
      • 2015-10-19
      • 1970-01-01
      • 2011-09-23
      相关资源
      最近更新 更多