在Django应用程序中查找主机和端口 [英] Find Host and Port in a Django Application

查看:122
本文介绍了在Django应用程序中查找主机和端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在连接到Twitter Streaming API,并正在设置OAuth握手.我需要请求令牌,然后将callback_url作为params字典与发布请求一起发送.

I'm connecting to the Twitter Streaming API and am setting up the OAuth handshake. I need to request a token and send a callback_url as a params dictionary along with post request.

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

I've hardcoded in the url for development (http://localhost:8000/oauth) but when I deploy this will change. 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)

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

I've tried using both the os and socket modules, and code is below:

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返回从集合中解开的元组的最后一个项目.

name returns the first element of the tuple above and ip returns the last item of the tuple unwrapped from the collection.

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

I'm looking for a return value of localhost or localhost:8000. I can work with either one.

推荐答案

调用文档:

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

HttpRequest.build_absolute_uri(location) Returns the absolute URI form of location. If no location is provided, the location will be set to request.get_full_path().

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

If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request.

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

这篇关于在Django应用程序中查找主机和端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆