Get Request Host Name Without Port in Flask


I’ve just managed to get my app server hostname in Flask using 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



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)

python 2

from urlparse import urlparse
o = urlparse("")
print(o.hostname)  # will display ''
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('')
URL(scheme='https', netloc='', path='/path/to/me', query='query1=x&query2', fragment='')
>>> url_parse('').host
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.