下面我给你 两个版本的"登录小程序" ,从 纯 Python 控制台版 到 Flask Web 版,你可以按需求选。
✅ 都是可直接运行的,适合练手和面试。
✅ 版本一:Python 控制台登录程序(新手必练)
功能
-
用户名 + 密码校验
-
最多 3 次重试
-
登录成功 / 失败提示
代码(直接复制运行)
# login.py
def login():
username = "admin"
password = "123456"
for i in range(3):
user = input("请输入用户名:")
pwd = input("请输入密码:")
if user == username and pwd == password:
print("✅ 登录成功!")
return True
else:
print(f"❌ 用户名或密码错误,还剩 {2 - i} 次机会")
print("🚫 登录失败次数过多,程序退出")
return False
if __name__ == "__main__":
login()
运行
python login.py
✅ 知识点拆解
| 点 | 说明 |
|---|---|
def login() |
定义方法 |
for i in range(3) |
限制登录次数 |
__name__ == "__main__" |
防止被导入时自动执行 |
return |
提前结束函数 |
✅ 版本二:Flask Web 登录程序(实战常用)
功能
-
浏览器登录
-
POST 表单提交
-
简单会话校验
-
登录成功后跳转
1️⃣ 安装 Flask
pip install flask
2️⃣ 项目结构
flask_login/
├── app.py
├── templates/
│ ├── login.html
│ └── index.html
└── static/
3️⃣ Flask 主程序(app.py)
from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = "dev_secret_key" # 生产环境要换成随机字符串
USERNAME = "admin"
PASSWORD = "123456"
@app.route("/", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
if username == USERNAME and password == PASSWORD:
session["user"] = username
return redirect(url_for("index"))
else:
return render_template("login.html", error="用户名或密码错误")
return render_template("login.html")
@app.route("/index")
def index():
if "user" not in session:
return redirect(url_for("login"))
return render_template("index.html", user=session["user"])
@app.route("/logout")
def logout():
session.pop("user", None)
return redirect(url_for("login"))
if __name__ == "__main__":
app.run(debug=True)
4️⃣ 登录页面(templates/login.html)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h2>用户登录</h2>
{% if error %}
<p style="color:red">{{ error }}</p>
{% endif %}
<form method="post">
用户名:<input type="text" name="username"><br><br>
密码:<input type="password" name="password"><br><br>
<button type="submit">登录</button>
</form>
</body>
</html>
5️⃣ 登录成功页(templates/index.html)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h2>欢迎你,{{ user }}!</h2>
<a href="{{ url_for('logout') }}">退出登录</a>
</body>
</html>
6️⃣ 运行
python app.py
✅ 两个版本对比
| 版本 | 场景 | 难度 |
|---|---|---|
| 控制台登录 | 初学 Python | ⭐ |
| Flask Web 登录 | Web 后端 / 面试 | ⭐⭐⭐ |
✅ 下一步你可以继续学
我可以继续帮你:
-
✅ 改成 JSON 接口(前后端分离)
-
✅ 连接 MySQL / SQLite 用户表
-
✅ 加密码加密(hash + salt)
-
✅ 加验证码
-
✅ 加装饰器 @login_required
-
✅ 改成 JWT 登录(企业常用)
👉 你是 刚学 Python ,还是 正在学 Flask 后端?
我可以直接按你的阶段给你下一个"进阶版本"。