2

是否可以在瓶子请求中以编程方式获取服务器的 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)
4

4 回答 4

4

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

@route('/file')
def getAFileLink():
    host = bottle.request.get_header('host')
    return {'url': 'http://{}/some/file.abc'.format(host)}
于 2013-06-04T02:12:50.357 回答
3

尝试一下bottle.request.url文档)。

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

于 2013-06-03T12:58:22.863 回答
2

您可以使用:

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

文档

于 2013-12-05T02:48:09.627 回答
1

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

import socket
socket.gethostbyname(socket.gethostname())
于 2013-06-03T12:49:41.113 回答