Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get 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 hostname with its port. I want to use field/method that returns only the hostname without having to do string replace, if any.

like image 607
M Rijalul Kahfi Avatar asked Apr 06 '14 02:04

M Rijalul Kahfi


People also ask

What is the default host port and port of Flask?

The default value is 5000 or it is the port number set in the SERVER_NAME config variable. Example: --host=127.0. 0.2 --port=1234 .

How do I run a Flask app on a different port?

Either identify and stop the other program, or use flask run --port 5001 to pick a different port. You can use netstat or lsof to identify what process id is using a port, then use other operating system tools stop that process. The following example shows that process id 6847 is using port 5000.

How do I change my default host and port in Flask?

To change the host and port that the Python flask command uses, we can use the -h flag to change the host and the -p flag to change the port. to run our flask app with the host set to localhost and the port set to 3000.


3 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'
like image 153
Juan E. Avatar answered Oct 20 '22 23:10

Juan E.


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
like image 14
Paul Brackin Avatar answered Oct 20 '22 21:10

Paul Brackin


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
like image 9
Vinayak Mahajan Avatar answered Oct 20 '22 21:10

Vinayak Mahajan