Flask Not Redirecting after POST?

Viewed 4188

I have been staring at this and Googling stuff for hours now, and I need another pair of eyes. I am learning Python and Flask.

My problem: Flask is not visibly changing the page after the returned redirect(), but it is "working": The printed messages "Successfully redirected to the homepage." and "User has a valid session." are being outputted to the console after login. Additionally, navigating to "/home" directly works as expected. I am using jQuery to POST data to Flask.

from flask import Flask, request, redirect, jsonify, render_template, session

from google.oauth2 import id_token
from google.auth.transport import requests

import sys, collections

import db

app = Flask(__name__)
app.secret_key = 'some-key'

db.connect('users.sqlite')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/collect', methods=['POST'])
def collect():
    if request.method == 'POST':
        google_credential_package = {}
        google_credential_package['google_credential'] = request.json['google_credential']
        google_credential_package['verified'] = request.json['verified']

        try:
            idinfo = id_token.verify_oauth2_token(google_credential_package['google_credential'], requests.Request(), 'my-client-id')
            if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
                raise ValueError('Wrong issuer.')
            if idinfo['aud'] == 'my-client-id':
                userid = idinfo['sub']
                email = idinfo['email']
                name = idinfo['name']
                pfp = idinfo['picture']
                user_type = 'normie'

                retrieved_user = db.user('users.sqlite', userid, email, name, pfp, user_type)

                if retrieved_user[3] == 'alpha':
                    print('User ' + name + ' is an Alpha Tester.')
                    session['user'] = 'yes'
                    return redirect('/home') # THE URL DOES NOT CHANGE HERE. (REDIRECT DOES NOT VISUALLY CHANGE ANYTHING.)
                else:
                    return 'Success.'
        except ValueError:
            print('Invalid token!')
            pass

@app.route('/home')
def generateHome():
    print('Successfully redirected to the homepage.')
    if session.get('user'):
        print('User has a valid session.')
        return render_template('home.html') # THIS DOES NOT HAPPEN VISIBLY.
    else:
        print('User does not have a valid session.')
        return render_template('error.html', error = 'This page is only available to Alpha users.')

EDIT: There is no error message outputted. The template "home.html" is stored in templates.

2 Answers

option one

just post your form using normal form post (ie form.submit(), or just have a submit button you do not intercept) and alow the backendd to redirect you to arrive at your destination

option two

do the redirect in javascript (document.location.href=new_url) after you get success ...

I would also recommend taking a better look at how clientside vs serverside works and how they interact together

jquery callbacks?:

success: function(response) {
                window.location.replace(`${response.data}`);
          },
error: function(error) {
                console.log(error);
       }
Related