简体   繁体   中英

get server address from bottle

Is it possible to get the IP Address of the server programmaticaly in a bottle request?

I need to return a link to a file on the server inside a request and need to know the IP. Bottle will be started on a server with different IPs and all of these IPs will be serve requests.

currently i looks like this:

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)

Give a try to bottle.request.url ( docs ).

In case you need only scheme and hostname, use urlparse to get it.

If your servers aren't behind a load balancer, just use the Host HTTP header.

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

you can use:

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

docs

Why are you running your server on the same ip as the link that you return?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM