Skip to content

Instantly share code, notes, and snippets.

@rsyring
Created August 15, 2024 06:02
Show Gist options
  • Save rsyring/c50a500a5d35787ef45c1ff1e78d8898 to your computer and use it in GitHub Desktop.
Save rsyring/c50a500a5d35787ef45c1ff1e78d8898 to your computer and use it in GitHub Desktop.
flask server_name issue
from flask import Flask, url_for
import pytest
@pytest.fixture
def app():
app = Flask(__name__)
@app.route('/')
def view():
return url_for('view', _external=True)
return app
@pytest.fixture()
def client(app):
return app.test_client()
def root_url(app: Flask, req_url=None):
if req_url is None:
with app.app_context():
return url_for('view')
resp = app.test_client().get(req_url)
if resp.status_code == 200:
return resp.text
return resp.status_code
def test_default(app: Flask):
assert root_url(app, '/') == 'http://localhost/'
assert root_url(app, 'http://example.com/') == 'http://example.com/'
assert root_url(app, 'http://www.example.com/') == 'http://www.example.com/'
assert root_url(app, 'http://bar.example.com/') == 'http://bar.example.com/'
assert root_url(app, 'http://flaskr.com/') == 'http://flaskr.com/'
with pytest.raises(RuntimeError) as excinfo:
root_url(app)
assert excinfo.match(
"Unable to build URLs outside an active request without 'SERVER_NAME' configured",
)
def test_servername(app: Flask):
app.config['SERVER_NAME'] = 'www.example.com'
assert root_url(app, '/') == 'http://www.example.com/'
assert root_url(app, 'http://example.com/') == 404
assert root_url(app, 'http://www.example.com/') == 'http://www.example.com/'
assert root_url(app, 'http://bar.example.com/') == 404
assert root_url(app, 'http://flask.com/') == 404
assert root_url(app) == 'http://www.example.com/'
def test_currently_impossible(app: Flask):
# Primary canonical app domain
assert root_url(app, 'http://www.example.com/') == 'http://www.example.com/'
# Acceptable alternate domain
assert root_url(app, 'http://www.demo.com/') == 'http://www.demo.com/'
# Servable legacy domain, but use canonical domain for external URLs
assert root_url(app, 'http://www.demo.com/') == 'http://www.example.com/'
# Use canonical domain
assert root_url(app) == 'http://www.example.com/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment