在Django应用中查找主机和端口
我正在连接Twitter的流媒体API,并设置OAuth的握手过程。我需要请求一个令牌,并将一个callback_url
作为参数字典发送在POST请求中。
在开发过程中,我把网址硬编码成了(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
返回的是元组中最后一个项,去掉了集合的包装。
我希望得到的返回值是localhost
或者localhost:8000
,这两个都可以。
1 个回答
1
调用 request.build_absolute_uri() 方法,然后提取出域名。
文档说明:
HttpRequest.build_absolute_uri(location) 这个方法会返回一个完整的 URI(统一资源标识符),也就是一个网址。如果没有提供具体的位置,默认会使用 request.get_full_path() 的结果。
如果你提供的位置本身就是一个完整的网址,它就不会被改变。否则,这个完整的网址会根据请求中可用的服务器信息来构建。
举个例子:"http://example.com/music/bands/the_beatles/?print=true"