【问题标题】:Flask Not Redirecting after POST?POST后烧瓶不重定向?
【发布时间】:2017-11-22 23:11:26
【问题描述】:

我已经盯着这个和谷歌搜索了好几个小时了,我需要另一双眼睛。我正在学习 Python 和 Flask。

我的问题:Flask 在返回 redirect() 后没有明显改变页面,但它正在“工作”:打印的消息“成功重定向到主页”。和“用户有一个有效的会话。”登录后正在输出到控制台。此外,导航到“/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.')

EDIT:没有输出错误信息。模板“home.html”存储在templates

【问题讨论】:

  • 不要使用 jquery ... 否则在收到您的回复(可能是重定向页面的内容)后,您将不得不在 javascript 中重定向(使用 document.location.href='/' )...仔细查看进入客户端与服务器端以及它们如何交互
  • 是的,响应已经是重定向页面的内容。这很有意义。谢谢你。您可以发布答案以便我接受吗?

标签: jquery python flask


【解决方案1】:

选项一

只需使用普通表单发布(即form.submit(),或者只使用您不拦截的提交按钮)发布您的表单,然后通过后端将您重定向到您的目的地

选项二

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

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

【讨论】:

    【解决方案2】:

    jquery 回调?:

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

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 2016-09-28
      • 2014-10-14
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多