I've just managed to get my app server hostname in Flask using request.host and request.url_root, but both field return the request hostname with its port.

I want to use field/method that returns only the request hostname without having to do string replace, if any.

有帮助吗?

解决方案

There is no Werkzeug (the WSGI toolkit Flask uses) method that returns the hostname alone. What you can do is use Python's urlparse module to get the hostname from the result Werkzeug gives you:

python 3

from urllib.parse import urlparse

o = urlparse(request.base_url)
print(o.hostname)

python 2

from urlparse import urlparse
    
o = urlparse("http://127.0.0.1:5000/")
print(o.hostname)  # will display '127.0.0.1'

其他提示

Building on Juan E's Answer, this was my

Solution for Python3:

from urllib.parse import urlparse
o = urlparse(request.base_url)
host = o.hostname

This is working for me in python-flask application.

from flask import Flask, request
print "Base url without port",request.remote_addr
print "Base url with port",request.host_url

If you want to use it on flask template (jinja2):

<!--Without port -->
{{ request.remote_addr }}

<!-- With port -->
{{ request.hostname }}

Actually, wekzeug.urls.url_parse() does provide a "host" property, though it is not displayed in the str() of the object:

>>> from werkzeug.urls import url_parse
>>> url_parse('https://auth.dev.xevo-dev.com:443/path/to/me?query1=x&query2')
URL(scheme='https', netloc='auth.dev.xevo-dev.com:443', path='/path/to/me', query='query1=x&query2', fragment='')
>>> url_parse('https://auth.dev.xevo-dev.com:443/path/to/me?query1=x&query2').host
'auth.dev.xevo-dev.com'
>>> 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top