flask简单的登录demo

xiaoxiao2022-07-06  11


某平台价值19860元的编程课程资料免费领取【点我领取】


flask框架(二):简单的登录demo

一:main.py

# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/3 22:58 from flask import Flask, render_template, request, redirect, session, url_for app = Flask(__name__) app.debug = True # 自动重启 USERS = { 1: {'name': '大白', 'age': '18', 'gender': '男', 'text': '非常可爱'}, 2: {'name': '小白', 'age': '20', 'gender': '男', 'text': '非常暖'}, 3: {'name': '张三', 'age': '21', 'gender': '女', 'text': '天下第一美'}, 4: {'name': '王五', 'age': '20', 'gender': '女', 'text': '帝国理工宅女'}, } @app.route('/detail/<int:nid>', methods=['GET']) # 动态url传入一个值 def detail(nid): user = session.get('user_info') if not user: url = url_for('l1') # 根据别名生成url return redirect(url) info = USERS[nid] return render_template('detail.html', info=info) # html 文件放在templates文件夹 @app.route('/login', methods=['GET', 'POST'], endpoint='l1') # endpoint 表示别名 def login(): if request.method == 'GET': return render_template('login.html') else: user = request.form.get('user') # 从表单中获取数据 pwd = request.form.get('pwd') if user == 'alex' and pwd == '123': session['user_info'] = user return redirect('http://www.baidu.com') # 跳转 return render_template('login.html', error='用户名或密码错误') # error对应着前面的模板语言error @app.route('/index', methods=['GET']) def index(): user = session.get('user_info') if not user: return redirect('/login') # 跳转到登录页 return render_template('index.html', user_dict=USERS) if __name__ == '__main__': app.run()

二:login.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户登录</h1> <form method="post"> <input type="text" name="user"> <input type="text" name="pwd"> <input type="submit" value="登录">{{error}} </form> </body> </html>

三:index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户列表</h1> <table> <!--从字典中循环读取键和值--> {% for k,v in user_dict.items() %} <tr> <td>{{k}}</td> <!--获取字典中的值有三种--> <td>{{v.name}}</td> <td>{{v['name']}}</td> <td>{{v.get('name')}}</td> <td><a href="/detail/{{k}}">查看详情</a></td> </tr> <!--结束循环--> {% endfor %} </table> </body> </html>

四:detail.html

 

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>详情信息:{{info.name}}</h1> <div> {{info.text}} </div> </body> </html>

转载请注明原文地址: https://www.6miu.com/read-4968544.html

最新回复(0)