Skip to main content
 首页 » 编程设计

python之从 Bottle 中获取服务器地址

2025年05月04日13lyj

是否可以在 bottle 请求中以编程方式获取服务器的 IP 地址?

我需要在请求中返回指向服务器上文件的链接,并且需要知道 IP。 Bottle 将在具有不同 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) 

请您参考如下方法:

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

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