重定向在Heroku上无法正常工作,但在localhost上却可以 [英] Redirects not working properly on Heroku but they do on localhost

查看:67
本文介绍了重定向在Heroku上无法正常工作,但在localhost上却可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发我的第一个Flask Web应用程序,该应用程序涉及登录,会话以及当然的重定向.这是一个Web应用程序,学校可以在其中登录并查看学生的欺凌报告.在localhost上,一切正常,但在heroku服务器上,一切正常.我在jinja中有一个带if语句的index.html:{%if session.user_id%}它显示了学校的索引,否则显示了常规索引问题是登录后返回常规索引或登录而不是重定向到学校索引".

i am developing my first flask web app that involves login, sessions and of course redirects. It is a webapp where schools can log in and view bullying reports from their students. On localhost everything works fine but in the heroku server it doesn't. Ihave an index.html with an if statement in jinja:{% if session.user_id %} it shows an index for schools, else it shows a general index The problem is that after loggin in it goes back to the general index or to login again instead of redirecting to the "schools index" .

这可能是由于Heroku无法识别会话[user_id] ??

Maybe this is caused because somehow Heroku fails to recognise the session[user_id]??

有时它成功地超出了登录名,但是当我再次重定向时,它只是忘记了会话并返回到常规索引或再次登录.有时,当按下注册按钮时,它又回到索引,忘记了会话.

Sometimes it goes beyond the login succesfully but when i redirect once more it just forgets the session and goes back to general index or login again. And also sometimes when the register button is pressed it just goes back to index forgetting the session.

如果您想尝试一下,这里是heroku链接: https://pure-harbor -99831.herokuapp.com/

Here is the heroku link if you want to try it out: https://pure-harbor-99831.herokuapp.com/

这是我的代码,下面我将输入我在日志中得到的错误

This is my code and below i will enter the errors i get on logs

import os
import time
import datetime
from flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for, session
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError, BadRequest
from werkzeug.security import check_password_hash, generate_password_hash
import sqlite3
from sqlite3 import Error
from flask_security import Security, login_required
from functools import wraps

app = Flask(__name__)
pp.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)
app.config["TEMPLATES_AUTO_RELOAD"] = True

def login_required(f):
    """
    Decorate routes to require login.

    http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get("user_id") is None:
            return redirect("/login")
        return f(*args, **kwargs)
    return decorated_function

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


@app.route("/regescuela", methods=["GET", "POST"])
def register():
    session.clear()
    if request.method == "POST":
        username = request.form.get("username").upper()
        dup_username = db.session.query(db.exists().where(Usuarios.username == username)).scalar()
        nombrescuela = request.form.get("nombrescuela").upper()
        dup_nombrescuela = db.session.query(db.exists().where(Usuarios.nombrescuela == nombrescuela)).scalar()

        if dup_username:
            return apology("Este usuario ya existe! Prueba con otro!")
        if dup_nombrescuela:
            return apology("Esta escuela ya ha sido registrada anteriormente!")
        if not request.form.get("mail"):
            return apology("No ha introducido el correo electrónico!")
        if not (request.form.get("provincia")):
            return apology("No ha introducido provincia.")
        if not request.form.get("nombrescuela"):
            return apology("No ha introducido el nombre de la escuela!")
        if "@" not in request.form.get("mail"):
            return apology("No ha introducido un correo electrónico valido!")
        if not request.form.get("username"):
            return apology("No ha introducido un nombre de usuario!")
        elif not request.form.get("password"):
            return apology("No ha introducido una contraseña!")
        elif request.form.get("password") != request.form.get("confirmation"):
            return apology("Las contraseñas no coinciden.")
    else:
        usumayu = request.form.get("username")
        return render_template("regescuela.html"
    nuevaentrada = Usuarios(nombrescuela = request.form.get("nombrescuela").upper(), username = request.form.get("username").upper(), hash = generate_password_hash(request.form.get("password")), provincia = request.form.get("provincia"), mail = request.form.get("mail"))
    db.session.add(nuevaentrada)
    db.session.commit()

    session["user_id"] = nuevaentrada

    flash("Registrado!")
    return redirect("/")@app.route("/check", methods=["GET"])



@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        username=request.form.get("username").upper()

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("Debe ingresar un nombre de usuario.", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("Debe ingresar una contraseña.", 403)



        # Ensure username exists and password is correct


        if rows is None or not check_password_hash(rows.hash, request.form.get("password")):
            return apology("Usuario o contraseña incorrectos", 403)

        # Remember which user has logged in
        session["user_id"] = rows.username #rows[0]["username"]
        session["nombrescuela"] = rows.nombrescuela


        # Redirect user to home page
        flash("Sesión Iniciada!")
        return redirect("/")


    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")

错误:

登录(localhost)时出现此错误:

I get this error when loggin in (localhost):

"POST /login HTTP/1.1" 302 - 

这是在Heroku中登录时的提示:

And this one when loggin in in Heroku :

2019-08-28T02:48:12.328933+00:00 heroku[router]: at=info method=POST path="/login" host=pure-harbor-99831.herokuapp.com request_id=5b9187f3-b253-40e5-8f98-d37be12bbc8b fwd="190.55.52.184" dyno=web.1 connect=0ms service=202ms status=302 bytes=583 protocol=https

也许我在帖子上做错了什么,但我不这么认为.我认为主要问题应该在于我一开始创建的"def login_required(f):",因为它总是返回到/login,就像session.get("user_id")为None一样.

Maybe i am doing something wrong with the post and get but i dont think so. I think the main problem should be in that "def login_required(f):" that i create at the beginning because it always goes back to /login like if session.get("user_id") was None.

但这很奇怪,因为在localhost中它总是输出错误,重定向工作正常,但是在heroku中,它输出错误,并且重定向不工作.

but it is weird because altough in localhost it outputs the error the redirects work fine, but in heroku it outputs the eror and the redirects dont work.

有任何线索吗?谢谢:)

Any clues? Thanks:)

推荐答案

您通常希望对url_for使用重定向.例如,在这种情况下,不要说redirect("/login"),而要执行redirect(url_for('login')).另外,请确保您从flask导入了url_for函数.

You would generally want to use redirect with url_for. For example in this case instead of saying redirect("/login"), do redirect(url_for('login')). Also, make sure that you import the url_for function from flask.

这篇关于重定向在Heroku上无法正常工作,但在localhost上却可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆