python的登陆认证及网页认证
思路
通过登陆---登陆通过将用户名称写入session--每个网页访问先认证用户是否在session中
flask登陆首页
from flask import Flask, render_template, request, redirect, url_for, session app = Flask(__name__) app.secret_key = 'your_secret_key_here' # 设置秘密密钥以安全地处理会话 # 假设我们有一个简单的用户验证函数 def check_credentials(username, password): # 这里只是一个简化的模拟,实际应用中应连接到数据库进行查询 if username == 'admin' and password == 'password': return True return False @app.route('/') def home(): if 'username' in session: return "Welcome back, {}!".format(session['username']) return "You are not logged in. Please go to the login page." @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') if check_credentials(username, password): session['username'] = username return redirect(url_for('home')) else: error_message = "Invalid credentials. Please try again." else: error_message = None return render_template('login.html', error=error_message) @app.route('/logout') def logout(): # 清除会话数据 session.pop('username', None) return redirect(url_for('home')) if __name__ == '__main__': app.run(debug=True)
登陆的网页代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{{ url_for('login') }}" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username"> <label for="password">Password:</label> <input type="password" id="password" name="password"> {% if error %} <p>{{ error }}</p> {% endif %} <button type="submit">Login</button> </form> </body> </html>
做一个决定,并不难,难的是付诸行动,并且坚持到底。