查找Django应用程序主机和端口(Find Host and Port in a Django A

2019-10-20 12:25发布

我连接到Twitter的流API和正在建立的OAuth握手。 我需要请求令牌并发送callback_url与后请求一起作为PARAMS字典。

我已经硬编码在url发展(http://localhost:8000/oauth)但是当我部署这种情况将会改变。 我想设置的东西,会发现主机和端口,并设置一个参考吧。 理想的情况下,看起来像"http://%s/oauth" % (domain_name)

我同时使用的操作系统和插座模块试过了,代码如下:

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 。 我可以与任何一个工作。

Answer 1:

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

文档:

HttpRequest.build_absolute_uri(位置)返回位置的绝对URI形式。 如果没有提供位置,该位置将被设置为request.get_full_path()。

如果该位置已经是一个绝对URI,它不会被改变。 否则,绝对URI用在这个要求提供的服务器变量构建。

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



文章来源: Find Host and Port in a Django Application