Search code examples
pythonflaskrequestporthostname

Get Request Host Name Without Port in Flask


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.


Solution

  • 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'