目录
- 前言
- Demo
前言
对于python用户的登录,以下只是提供一个Demo用于学习
更多的python知识点可从我的专栏中进行学习
- python专栏
- 详细分析Flask中的蓝图Blueprint(附Demo)
- 详细分析Flask部署云服务器(图文介绍)
- 构建Flask前后端不分离项目(附Python Demo)
Demo
项目结构:
/project-directory
/templates
login.html
app.py
前端登录页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
.container {
width: 300px;
margin: 100px auto;
padding: 20px;
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
}
.form-group input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.form-group button {
width: 100%;
padding: 10px;
background-color: #5cb85c;
color: white;
border: none;
cursor: pointer;
}
.error {
color: red;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2>Login</h2>
<form method="POST" action="/login">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
</div>
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
<div class="form-group">
<button type="submit">Login</button>
</div>
</form>
</div>
</body>
</html>
后端应用:
from flask import Flask, render_template, request, redirect, url_for, flash, session
app = Flask(__name__)
app.secret_key = 'your_secret_key' # 用于会话加密,可以换成自己的密钥
# 假设的用户数据,实际应用应从数据库中获取
users = {
'admin': '123456',
'ma': 'nong'
}
@app.route('/')
def index():
if 'username' in session:
return f'Logged in as {session["username"]}. <a href="/logout">Logout</a>'
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# 检查用户名和密码
if username in users and users[username] == password:
session['username'] = username
return redirect(url_for('index'))
else:
error = 'Invalid username or password.'
return render_template('login.html', error=error)
return render_template('login.html')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
账号和密码分别是这两个
- 账号:admin,密码: 123456
- 账号:ma ,密码:nong
登录成功后:
包括登录失败 以及 字段没有输入的捕捉情况: