flask 模拟简单的登录功能(1)

模拟简单的登录功能

首先,在app.py中定义路由,用户访问根路径时,渲染 login.html 页面。输入用户名密码点击提交后,判断用户名密码是否正确,正确则提示登录成功,否则将报错信息显示在页面上

python 复制代码
from flask import Flask,redirect,url_for,request,render_template
app = Flask(__name__)

# 根路径
@app.route('/')
def index():
    return render_template('login.html')

# 登录成功
@app.route('/success/<name>')
def success(name):
    return f'welcome {name}!<a href = "/">点击重新登录</a>'

# 直接访问 http://localhost:5000/login ,或者点击提交登录信息后的处理逻辑
@app.route('/login',methods=['POST','GET'])
def login():
    error = None
    if request.method == 'POST':
        user = request.form['username']
        if request.form['username'] != 'admin' or request.form['password'] != 'admin':
            error = '用户名或密码错误,请重试!'
        else:
            print(user)
            return redirect(url_for('success',name = user))
    return render_template('login.html',error = error)

if __name__ == '__main__':
   app.run(debug=True)

login.html 页面入下:

html 复制代码
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form action="http://localhost:5000/login" method="post">
        <table>
            <tr>
                <td>Username</td>
                <td><input type="username" name="username"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"></td>
            </tr>
        </table>
    </form>
    {% if error %}
    <p><strong>Error</strong>:{{error}}</p>
    {% endif %}
</body>
</html>

这样,一个简单的登录功能就做好了。运行app.py,在浏览器输入 http://localhost:5000 即可查看效果。

相关推荐
浮尘笔记2 分钟前
Go语言临时对象池:sync.Pool的原理与使用
开发语言·后端·golang
52Hz1181 小时前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
梦梦代码精1 小时前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
weixin_462446232 小时前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
REDcker2 小时前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
百***78753 小时前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_942191774 小时前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python
没有bug.的程序员4 小时前
Java 序列化:Serializable vs. Protobuf 的性能与兼容性深度对比
java·开发语言·后端·反射·序列化·serializable·protobuf
忧郁的橙子.5 小时前
26期_01_Pyhton基本语法
python