I have a flask app running in a docker container. All works fine, except when I want to do some manual jobs in the same docker container from flask shell. The problem is that the url_for(x, _external=True)
always returns https://localhost, doesn't matter how I try to set the server name in the shell.
I have obviously tried setting the SERVER_NAME to no change.
$ python manage.py shell
>>> from flask import current_app
>>> current_app.config['SERVER_NAME'] = 'example.com'
>>> from app import models
>>> models.Registration.send_registration(id=123)
The jinja template is having:
{{ url_for('main.index', _external=True, _scheme='https') }
}
Which generates: https://localhost
I would like to get: https://example.com
I am using Flask 0.11, Werkzeug 0.11.10 and Jinja2 2.8
Your app uses the SERVER_NAME
defined when the application context was created.
If you want to do it in a shell, you can create a test request context after you set the SERVER_NAME
.
>>> from flask import current_app, url_for
>>> current_app.config['SERVER_NAME'] = 'example.com'
>>> with current_app.test_request_context():
... url = url_for('index', _external=True)
...
>>> print url
http://example.com/
We can dig in Flask code to understand it.
Flask url_for
uses the appctx.url_adapter
to build this URL. This url_adapter
is defined when the AppContext
is initialized, and it happens when the shell is started. It calls the app.create_url_adapter
and it uses the defined SERVER_NAME
.
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