POST后烧瓶不重定向?

时间:2017-11-22 23:11:26

标签: jquery python flask

我一直在盯着这个和谷歌搜索的东西几个小时,我需要另一双眼睛。我正在学习Python和Flask。

我的问题:Flask在返回的重定向()之后没有明显改变页面,但它是"工作":打印的消息"成功重定向到主页。"和"用户有一个有效的会话。"登录后输出到控制台。此外,导航到" / home"直接按预期工作。我正在使用jQuery将数据发布到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.')

编辑:没有输出错误消息。模板" home.html"存储在templates

2 个答案:

答案 0 :(得分:2)

选项一

只需使用普通表单发布您的表单(例如form.submit(),或者只是有一个您不拦截的提交按钮),并允许后端重定向您到达目的地

选项二

在获得成功后,在javascript(document.location.href=new_url)中进行重定向...

我还建议您更好地了解客户端与服务器端的工作方式以及它们如何相互作用

答案 1 :(得分:0)

jquery回调?:

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