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.
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 .
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.
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.
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'
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With