Flask Internal Redirect with parameters



examples/flask/redirect-with-parameters/app.py
from flask import Flask, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return '''<form action="/goto" method="POST">
            <input name="username">
            <input type="submit" value="Go">
        </form>'''

@app.route('/goto', methods=['POST'])
def login_post():
    username = request.form.get('username')
    if username is None or username == '':
        return redirect(url_for('user_page_central'))
    return redirect(url_for('user_page', name = username))

@app.route('/user/')
def user_page_central():
    return 'List of users'

@app.route('/user/<name>')
def user_page(name):
    return f'Page of {name}'

examples/flask/redirect-with-parameters/test_app.py
import app

def test_app():
    web = app.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'<form action="/goto" method="POST">' in rv.data

    rv = web.post('/goto', data={'username': 'Joe'})
    assert rv.status == '302 FOUND'
    assert rv.headers['Location'] == 'http://localhost/user/Joe'
    assert b'<p>You should be redirected automatically to target URL: <a href="/user/Joe">/user/Joe</a>' in rv.data

    rv = web.post('/goto')
    assert rv.status == '302 FOUND'
    assert rv.headers['Location'] == 'http://localhost/user/'
    assert b'<p>You should be redirected automatically to target URL: <a href="/user/">/user/</a>' in rv.data

    rv = web.get('/user/Jane')
    assert rv.status == '200 OK'
    assert rv.data == b'Page of Jane'

    rv = web.get('/user/')
    assert rv.status == '200 OK'
    assert rv.data == b'List of users'