Setting SERVER_NAME has two major effects on url_for
and routing.
url_for
Usually SERVER_NAME
is set to enable url_for where request context is not available.
Setting a SERVER_NAME also by default enables URL generation without a request context but with an application context.
Without application context, you will bump into
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
Without request context, you will bump into
RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.
You can utilize the following code to get the application context and fake/test request context to enable url_for
.
app = Flask(__name__)with app.app_context(), app.test_request_context(): url = url_for('home')
NOTE: If you use _external=True
parameter for the above code, localhost
is always returned as SERVER/DOMAIN name.
routing
Once you set SERVER_NAME, Flask can only serve request from one single domain and return 404 for other domains.
If SERVER_NAME = 'mydomain.com'
, it won't serve request from www.mydomain.com
or mydomain.appspot.com
.
References: