11

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.

duhaime
  • 25,611
  • 17
  • 169
  • 224
M Rijalul Kahfi
  • 1,460
  • 3
  • 22
  • 42

5 Answers5

14

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'
Juan E.
  • 1,808
  • 16
  • 28
  • This doesn't get the hostname, is just shows how to remove the port number from the hostname once you have the hostname – duhaime Jun 15 '20 at 18:46
  • @duhaime the question said "both field return hostname with its port", so I answered the posted question. If you need something different you should look for the appropriate question or ask it yourself.. – Juan E. Jun 15 '20 at 23:25
14

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
Paul Brackin
  • 339
  • 3
  • 5
10

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
Vinayak Mahajan
  • 219
  • 3
  • 10
0

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

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

<!-- With port -->
{{ request.hostname }}
mrroot5
  • 1,811
  • 3
  • 28
  • 33
0

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'
>>> 
Sam
  • 101
  • 1
  • 5