M Rijalul Kahfi
M Rijalul Kahfi

Reputation: 1490

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.

Upvotes: 11

Views: 38024

Answers (5)

Juan E.
Juan E.

Reputation: 1819

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'

Upvotes: 15

Sam
Sam

Reputation: 297

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

Upvotes: 0

Paul Brackin
Paul Brackin

Reputation: 339

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

Upvotes: 14

mrroot5
mrroot5

Reputation: 1971

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

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

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

Upvotes: 0

Vinayak Mahajan
Vinayak Mahajan

Reputation: 219

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

Upvotes: 10

Related Questions