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?