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 即可查看效果。

相关推荐
kobe_OKOK_26 分钟前
DRF接口幂等操作
python·django
SomeB1oody34 分钟前
【RustyML入门】6.3. 并行归约
开发语言·后端·机器学习·rust·教程
廿士1 小时前
python脚本使用相关
python
青 春 记 忆1 小时前
零基础入门python19:Flask账本第一步——应用工厂、蓝图和健康检查
python·flask·后端开发
朦胧之1 小时前
Python 后端核心知识
python
Profile排查笔记1 小时前
指纹浏览器哪个好?从 Profile、代理、权限和自动化能力判断是否适合
前端·人工智能·后端·自动化
用户938515635072 小时前
用 AI 结对编程从 0 搭一个"单词后台管理系统":Next.js + Supabase + Drizzle + shadcn/ui 全记录
后端·postgresql·next.js
denggun123452 小时前
yield
前端·数据库·python
爱学习的小邓同学2 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
zx_741484813 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python