我正在开发我的第一个Flask Web应用程序,该应用程序涉及一些登录,会话以及重定向。这是一个Web应用程序,学校可以登录并查看学生的欺负报告。在localhost上,一切正常,但是在登录后在heroku服务器中,它返回到常规索引,而不是“ schools索引”。
这可能是由于Heroku无法识别会话[]引起的???我还有一个index.html,如果用户登录,则显示一部分,而不是全部,这可能是导致问题的原因。 但是我不认为可能是因为它在localhost上能很好地工作。
问题在于有时它会成功超过登录名,但是当我再次重定向时,它只会忘记会话并返回索引。
如果您想尝试一下,这里是heroku链接:https://pure-harbor-99831.herokuapp.com/
在这里,我将添加我的app.py和index.html的主要重定向:
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
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("/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)
# Query database for username
# rows = db.session.query(db.exists().where(Usuarios.username == username)).scalar()
#rowpass = db.session.query.filter_by(Usuarios.username = username).all()
rows = Usuarios.query.filter_by(username=username).first()
# rowpass = db.session.query(Usuarios.filter_by(Usuarios.username == username)).first()
# rows = db.execute("SELECT * FROM usuarios WHERE username = :username",
# username=request.form.get("username").upper())
# Ensure username exists and password is correct
#if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
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("/")
@app.route("/tablavictimas")
@login_required
def tablavictimas():
#acordate que aca cambiaste sessionuser_id por sessionnombrescuela y fijate si sirve si no volve al sessionuser_id
escuela = session["nombrescuela"].upper()
hechos = Victimas.query.filter_by(escuela=escuela).all()
hay = db.session.query(db.exists().where(Victimas.escuela == escuela)).scalar()
hechitos = Victimas.query.filter_by(escuela=escuela).order_by(Victimas.curso).all()
#hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["nombrescuela"])
#hechitos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela GROUP BY curso", escuela=session["nombrescuela"])
if not hay:
return apology("No se han recibido reportes aún.")
return render_template("tablavictimas.html", hechos=hechos, hechitos=hechitos)
@app.route("/tablatestigos", methods=["GET", "POST"])
@login_required
def tablatestigos():
escuela = session["nombrescuela"].upper()
hechos = Testigos.query.filter_by(escuela=escuela).all()
hay = db.session.query(db.exists().where(Testigos.escuela == escuela)).scalar()
hechitos = Testigos.query.filter_by(escuela=escuela).order_by(Testigos.curso).all()
#hechos = db.execute("SELECT * FROM testigos WHERE escuela = :escuela", escuela=session["nombrescuela"])
#hechitos = db.execute("SELECT * FROM testigos WHERE escuela = :escuela GROUP BY curso", escuela=session["nombrescuela"])
if not hay:
return apology("No se han recibido reportes aún.")
return render_template("tablatestigos.html", hechos=hechos, hechitos=hechitos)
Index.html只是扩展了一个这样的布局:
{% if session.user_id %}
<a href="/"> <img src="https://i.ibb.co/2kV28jg/palabraslogofinal.png" alt="logo" id="palabraslogo"> </a>
<a class="navbar-brand" href="/" class="escuelastitulo"> <b> <span class="blue" style="position: relative; top: -8px; font-size: 40px;">Escuelas</span> </b> </a>
<ul class="navbar-nav mr-auto mt-2">
<li class="nav-item"><a class="nav-link" href="/reportesrecibidos" style="color:#000000; position: relative; top: -8px; font-size:18px;">Reportes Recibidos</a></li>
</ul>
<ul class="navbar-nav ml-auto mt-2">
<li class="nav-item"><a class="nav-link" href="/logout">Cerrar Sesión</a></li>
</ul>
{% else %}
<!-- <a class="navbar-brand" href="/"><span class="blue">B</span><span class="red">u</span><span class="yellow">l</span><span class="green">l</span><span class="red">yng</span></a> -->
<a href="/"> <img src="https://i.ibb.co/2kV28jg/palabraslogofinal.png" alt="logo" id="palabraslogo"> </a>
<ul class="navbar-nav mr-auto mt-2">
<ul class="navbar-nav mr-auto mt-2">
<li class="nav-item"><a class="nav-link" href="/logreg" style="color:#000000; font-size:18px;">Escuela</a></li>
<li class="nav-item"><a class="nav-link" href="/elegi" style="color:#000000; font-size:18px;">Estudiante</a></li>
<li class="nav-item"><a class="nav-link" href="/psicologo" style="color:#000000; font-size:18px;">Hablar gratis con un psicologo</a></li>
<li class="nav-item"><a class="nav-link" href="/argentina" style="color:#000000; font-size:18px;">Bullying en Argentina</a></li>
</ul>
{% endif %}
这是我在日志中遇到的错误: 首先是302:
"POST /login HTTP/1.1" 302 209 "https://pure-harbor-99831.herokuapp.com/login"
然后出现错误:
http_error="Invalid HTTP status line" at=error code=H17 desc="Poorly formatted HTTP response" method=GET path="/tablatestigos" host=pure-harbor-99831.herokuapp.com request_id=d32a433d-0607-4c59-bebe-76856c2eea99 fwd="190.55.52.184" dyno=web.1 connect=1ms service=17ms status=503 bytes=325 protocol=https
有任何线索吗?谢谢:)