Get Request Host Name Without Port in Flask

Question:

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.

Asked By: M Rijalul Kahfi

||

Answers:

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'
Answered By: Juan E.

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
Answered By: Vinayak Mahajan

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

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

<!-- With port -->
{{ request.hostname }}
Answered By: mrroot5

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
Answered By: Paul Brackin

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'
>>> 
Answered By: Sam
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.