繁体   English   中英

在Django应用程序中查找主机和端口

[英]Find Host and Port in a Django Application

我正在连接到Twitter Streaming API,并正在设置OAuth握手。 我需要请求一个令牌,并发送一个callback_url作为params字典以及发布请求。

我已经将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的返回值。 我可以和任何一个一起工作。

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

文档:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM