1

I have a certain use case where a Flask app is not configured with SERVER_NAME and it resides in a subpath (say, http://example.com/subpath/subpath2), and, from within a request context, I need to extract just the http://example.com.

I noticed that, without SERVER_NAME being set in the Flask config, url_for with _external=True is still able to retrieve the full URL including the domain on which the Flask app is being served. So I figured there must be a way that Flask (or Werkzeug) retrieves the domain. I dug around inside the url_for function and what resulted was this function which I made to get the domain from within a request context.

from flask.globals import _request_ctx_stack

def get_domain():
    fragments = [
        _request_ctx_stack.top.url_adapter.url_scheme,
        _request_ctx_stack.top.url_adapter.get_host(''),
    ]
    return '://'.join(fragments)

I realise I'm accessing private members, but there is no other obvious way to do it that I could find. Is this the correct way to do it?

Hooloovoo13
  • 241
  • 2
  • 12

1 Answers1

0

If you wanna know the host domain name (example.com, by example) I recommend you to check this other StackOverflow question: Get Request Host Name Without Port in Flask

It uses urllib.parse to parse the full requested URL and get the host name.

If the answer seems unclear, there is my Minimal Reproductible Code (from the same question, but edited) for Python3:

import flask, urllib.parse
app = flask.Flask('MyWebApp')
@app.route('/')
def home():
    return "Host domain name is: " + str(urllib.parse.urlparse(flask.request.base_url).hostname)
app.run(host='0.0.0.0',port=80)

If you need to get http://example.com instead of example.com, just add it with a code like that hostname = "http://" + hostname.

HGStyle
  • 13
  • 5