我正在尝试在应用程序中设置会话,但它似乎无法正常工作。登录后,会话显示在Devtools上,但它不会像我们想象的那样重定向到/index
。
以下是我所做的:
app.py
from flask import Flask, render_template, redirect, url_for, request, session, flash
from functools import wraps
app = Flask(__name__)
app.secret_key = "gr3hu39ud3n89ud893e4"
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('You need to login first')
return redirect(url_for('login'))
return wrap
@app.route("/")
@login_required
def home():
return render_template('index.html')
@app.route('/welcome')
def welcome():
return render_template('welcome.html')
@app.route('/login', methods=('GET', 'POST'))
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invalid credentials. Please try again'
else:
session['logged_in'] = True
flash('You were just logged in!')
return redirect(url_for('home'))
return render_template('login.html', error=error)
@app.route('/logout')
@login_required
def logout():
session.pop('logged_in', None)
flash('You were just logged out!')
return redirect(url_for('welcome'))
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
模板/ welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/bootstrap.css.map">
</head>
<body>
<div class="container">
<h1>Welcome to flask</h1>
<p>Click <a href="/">Here</a> to go home</p>
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
</body>
</html>
模板/ index.html中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/bootstrap.css.map">
</head>
<body>
<div class="container">
<h1>Welcome to flask</h1>
<p>Click <a href="/logout">Here</a> to go Logout</p>
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
</body>
</html>
模板/ login.html的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/bootstrap.css.map">
</head>
<body>
<div class="container">
<h1>Please Login</h1>
<br>
<form action="">
<input type="text" placeholder="Username" name="username" value="{{ request.form.username }}">
<input type="password" placeholder="Password" name="password" value="{{ request.form.password }}">
<input type="submit" class="btn btn-default" value="Login">
</form>
{% if error %}
<p class="error"><strong>Error</strong>{{error}}</p>
{% endif %}
</div>
</body>
</html>
答案 0 :(得分:1)
登录脚本中的<form>
没有method
属性。如果没有method
属性,form
默认使用GET
。
在templates / login.html中尝试:
...
<form method="POST" action="">
...
参考: