从瓶子获取服务器地址

时间:2013-06-03 12:29:10

标签: python bottle

是否可以在瓶子请求中获得服务器的IP地址?

我需要在请求中返回服务器上文件的链接,并且需要知道IP。瓶子将在具有不同IP的服务器上启动,所有这些IP都将是服务请求。

目前我看起来像这样:

from bottle import *
import json
@get('/file')
def getAFileLink():
    # some logic here for the right filename to return
    # server runs now on e.g. 10.0.0.1 and 10.10.0.1
    # every client should see the IP from the server in the right subnet
    return json.dumps({'url': 'http://127.0.0.1:1337/some/file.abc'})

@route('/some/<filename>')
def getStaticFile(filename):
    return static_file(filename, root="/srv/static/files")

if __name__ == "__main__":
    run(host='0.0.0.0', port=1337)

4 个答案:

答案 0 :(得分:2)

尝试bottle.request.urldocs)。

如果您只需要方案和主机名,请使用urlparse来获取它。

答案 1 :(得分:2)

如果您的服务器不在负载均衡器后面,只需使用Host HTTP标头。

@route('/file')
def getAFileLink():
    host = bottle.request.get_header('host')
    return {'url': 'http://{}/some/file.abc'.format(host)}

答案 2 :(得分:2)

你可以使用:

from bottle import request 
urlparts = request.urlparts
print urlparts.scheme
print urlparts.netloc

docs

答案 3 :(得分:1)

为什么在与返回的链接相同的ip上运行服务器?

import socket
socket.gethostbyname(socket.gethostname())