简体   繁体   English

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

[英]Find Host and Port in a Django Application

I'm connecting to the Twitter Streaming API and am setting up the OAuth handshake. 我正在连接到Twitter Streaming API,并正在设置OAuth握手。 I need to request a token and send a callback_url as a params dictionary along with post request. 我需要请求一个令牌,并发送一个callback_url作为params字典以及发布请求。

I've hardcoded in the url for development (http://localhost:8000/oauth) but when I deploy this will change. 我已经将URL硬编码用于开发(http://localhost:8000/oauth)但是在部署时,它会改变。 I want to set up something that will find the host and port and set a reference it. 我想设置一些可以找到主机和端口的东西,并为其设置一个引用。 Ideally, looking like "http://%s/oauth" % (domain_name) 理想情况下,看起来像"http://%s/oauth" % (domain_name)

I've tried using both the os and socket modules, and code is below: 我试过同时使用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 returns ('justins-mbp-2.local.tld', ['145.15.168.192.in-addr.arpa'], ['192.168.15.145']) domain返回('justins-mbp-2.local.tld', ['145.15.168.192.in-addr.arpa'], ['192.168.15.145'])

name returns the first element of the tuple above and ip returns the last item of the tuple unwrapped from the collection. name返回上面的元组的第一个元素, ip返回从集合中解开的元组的最后一个项目。

I'm looking for a return value of localhost or localhost:8000 . 我正在寻找localhostlocalhost:8000的返回值。 I can work with either one. 我可以和任何一个一起工作。

call request.build_absolute_uri() , then extract the domain. 调用request.build_absolute_uri() ,然后提取域。

docs: 文档:

HttpRequest.build_absolute_uri(location) Returns the absolute URI form of location. HttpRequest.build_absolute_uri(location)返回location的绝对URI形式。 If no location is provided, the location will be set to request.get_full_path(). 如果未提供任何位置,则该位置将设置为request.get_full_path()。

If the location is already an absolute URI, it will not be altered. 如果该位置已经是绝对URI,则不会更改。 Otherwise the absolute URI is built using the server variables available in this request. 否则,将使用此请求中可用的服务器变量来构建绝对URI。

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

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

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