Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask shell - how to set server name for url_for _external=True?

Tags:

flask

jinja2

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

like image 288
Zoltan Fedor Avatar asked Dec 18 '22 16:12

Zoltan Fedor


1 Answers

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.

like image 187
iurisilvio Avatar answered Mar 23 '23 02:03

iurisilvio