如何建网站吗?微信小程序开发多少钱
你提供的代码是一个基本的Flask应用程序,实现了一个简单的登录系统。以下是代码的详细解释:
1. 导入必要的模块:`os` 用于生成密钥,`Flask` 用于创建Web应用程序。
2. 创建Flask应用程序的实例,并为会话管理设置一个密钥。
3. 定义管理员的默认用户名和密码。
4. 定义登录路由('/'),处理GET和POST请求。
- 如果请求方法是POST,它会获取包含用户名和密码的JSON数据。
- 然后它会检查提供的用户名和密码是否与默认用户名和密码匹配。
- 如果凭据有效,它会将用户名存储在会话中。
这个应用程序还包括其他几个路由:
- `/welcome` 路由用于显示欢迎页面,只处理GET请求。它会检查用户是否已登录,如果已登录,则显示欢迎页面,否则重定向到登录页面。
- `/home` 路由用于显示主页,只处理GET请求。它会检查用户是否已登录,如果已登录,则显示主页,否则返回一个JSON响应表示无权限访问主页。
- `/logout` 路由用于注销用户,它会清除会话数据并重定向到登录页面。
如果你运行这个应用程序,它将在本地启动一个Web服务器,并监听默认的端口(通常是5000)。你可以通过访问`http://localhost:5000`来访问登录页面。
项目结构
app.py
import os
from flask import Flask, render_template, request, redirect, url_for, session, jsonifyapp = Flask(__name__)
app.secret_key = os.urandom(24)# 默认的管理员账号和密码
default_username = 'admin'
default_password = 'admin123'# 路由:登录页面
@app.route('/', methods=['GET', 'POST'])
def login():if request.method == 'POST':# 获取 JSON 数据data = request.get_json()# 获取账号和密码username = data.get('username')password = data.get('password')# 验证账号和密码if username == default_username and password == default_password:# 将用户信息存储到 session 中session['username'] = usernamereturn jsonify({'message': '登录成功'})else:return jsonify({'message': '账号或密码错误'})return render_template('login.html')# 路由:欢迎页面
@app.route('/welcome', methods=['GET'])
def welcome():# 检查用户是否已经登录if 'username' in session:return render_template('welcome.html', username=session['username'])else:return redirect(url_for('login'))# 路由:主页
@app.route('/home', methods=['GET'])
def home():# 检查用户是否已经登录if 'username' in session:return render_template('home.html', username=session['username'])else:return jsonify({'message': '无权限访问主页'})# 路由:注销
@app.route('/logout')
def logout():# 清除 session 数据session.pop('username', None)return redirect(url_for('login'))if __name__ == '__main__':app.run()
templates / login.html
<!DOCTYPE html>
<html>
<head><title>Login</title>
</head>
<body><h1>Login</h1><form id="loginForm"><label for="username">Username:</label><input type="text" id="username" name="username" required><br><label for="password">Password:</label><input type="password" id="password" name="password" required><br><button type="submit">Login</button></form><div id="message"></div><script>document.getElementById("loginForm").addEventListener("submit", function(event) {event.preventDefault();var username = document.getElementById("username").value;var password = document.getElementById("password").value;var data = {"username": username,"password": password};fetch("/", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify(data)}).then(response => response.json()).then(data => {document.getElementById("message").innerText = data.message;if (data.message === "登录成功") {window.location.href = "/welcome";}}).catch(error => {console.error("Error:", error);});});</script>
</body>
</html>
templates / welcome.html
<!DOCTYPE html>
<html>
<head><title>Welcome</title>
</head>
<body><h1>Welcome, {{ username }}!</h1><p>You have successfully logged in.</p><a href="/home">Go to Home</a><br><a href="/logout">Logout</a>
</body>
</html>
templates / home.html
<!DOCTYPE html>
<html>
<head><title>Home</title>
</head>
<body><h1>Welcome, {{ username }}!</h1><p>This is the home page.</p><a href="/logout">Logout</a>
</body>
</html>
testcase.py
import requestssession = requests.Session()def login():data = {"username": "admin","password": "admin123"}url = 'http://127.0.0.1:5000'res = session.request(url=url, method='post', json=data)return sessiondef Welcome():url ='http://127.0.0.1:5000/welcome'res = login().get(url=url)print(res.text)def index_login():url = 'http://127.0.0.1:5000/home'res = login().request(url=url, method='get')print(res.text)def index_notlogin():url = 'http://127.0.0.1:5000/home'res = requests.get(url=url)print(res.json())