侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Flask框架通过Flask_login实现用户登录功能示例

技术  /  管理员 发布于 8年前   392

本文实例讲述了Flask框架通过Flask_login实现用户登录功能。分享给大家供大家参考,具体如下:

通过Flask_Login实现用户验证登录,并通过login_required装饰器来判断用户登录状态来判断是否允许访问视图函数。

运行环境:

python3.5
Flask 0.12.2
Flask_Login 0.4.1
Flask-WTF 0.14.2
PyMySQL 0.8.0
WTForms 2.1
DBUtils 1.2

目录结构:

直接看代码,具体功能有注释

Model/User_model.py

#创建一个类,用来通过sql语句查询结果实例化对象用class User_mod(): def __init__(self):  self.id=None  self.username=None  self.task_count=None  self.sample_count=None def todict(self):  return self.__dict__#下面这4个方法是flask_login需要的4个验证方式 def is_authenticated(self):  return True def is_active(self):  return True def is_anonymous(self):  return False def get_id(self):  return self.id # def __repr__(self): #  return '<User %r>' % self.username

templates/login.html

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <div class="login-content">  <form class="margin-bottom-0" action="{{ action }}" method="{{ method }}" id="{{ formid }}">   {{ form.hidden_tag() }}   <div class="form-group m-b-20">    {{ form.username(class='form-control input-lg',placeholder = "用户名") }}   </div>   <div class="form-group m-b-20">    {{ form.password(class='form-control input-lg',placeholder = "密码") }}   </div>   <div class="checkbox m-b-20">    <label>     {{ form.remember_me() }} 记住我    </label>   </div>   <div class="login-buttons">    <button type="submit" class="btn btn-success btn-block btn-lg">登 录</button>   </div>  </form> </div></body></html>

User_dal/dal.py

import pymysqlfrom DBUtils.PooledDB import PooledDBPOOL = PooledDB( creator=pymysql, # 使用链接数据库的模块 maxconnections=6, # 连接池允许的最大连接数,0和None表示不限制连接数 mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建 maxcached=5, # 链接池中最多闲置的链接,0和None不限制 maxshared=3, # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。 blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错 maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host='192.168.20.195', port=3306, user='root', password='youpassword', database='mytest', charset='utf8')class SQLHelper(object): @staticmethod def fetch_one(sql,args):  conn = POOL.connection() #通过连接池链接数据库  cursor = conn.cursor() #创建游标  cursor.execute(sql, args) #执行sql语句  result = cursor.fetchone() #取的sql查询结果  conn.close() #关闭链接  return result @staticmethod def fetch_all(self,sql,args):  conn = POOL.connection()  cursor = conn.cursor()  cursor.execute(sql, args)  result = cursor.fetchone()  conn.close()  return result

User_dal/user_dal.py

from Model import User_modelfrom User_dal import dalfrom User_dal import user_dalclass User_Dal: persist = None #通过用户名及密码查询用户对象 @classmethod def login_auth(cls,username,password):  print('login_auth')  result={'isAuth':False}  model= User_model.User_mod() #实例化一个对象,将查询结果逐一添加给对象的属性  sql ="SELECT id,username,sample_count,task_count FROM User WHERE username ='%s' AND password = '%s'" % (username,password)  rows = user_dal.User_Dal.query(sql)  print('查询结果>>>',rows)  if rows:   result['isAuth'] = True   model.id = rows[0]   model.username = rows[1]   model.sample_count = rows[2]   model.task_count = rows[3]  return result,model #flask_login回调函数执行的,需要通过用户唯一的id找到用户对象 @classmethod def load_user_byid(cls,id):  print('load_user_byid')  sql="SELECT id,username,sample_count,task_count FROM User WHERE id='%s'" %id  model= User_model.User_mod() #实例化一个对象,将查询结果逐一添加给对象的属性  rows = user_dal.User_Dal.query(sql)  if rows:   result = {'isAuth': False}   result['isAuth'] = True   model.id = rows[0]   model.username = rows[1]   model.sample_count = rows[2]   model.task_count = rows[3]  return model #具体执行sql语句的函数 @classmethod def query(cls,sql,params = None):  result =dal.SQLHelper.fetch_one(sql,params)  return result

denglu.py  flask主运行文件

from flask import Flask,render_template,redirectfrom flask_login import LoginManager,login_user,login_required,current_userfrom flask_wtf.form import FlaskFormfrom wtforms import StringField, PasswordField, BooleanFieldfrom wtforms.validators import Length,DataRequired,Optionalfrom User_dal import user_dalapp = Flask(__name__)#项目中设置flask_loginlogin_manager = LoginManager()login_manager.init_app(app)app.config['SECRET_KEY'] = '234rsdf34523rwsf'#flask_wtf表单class LoginForm(FlaskForm): username = StringField('账户名:', validators=[DataRequired(), Length(1, 30)]) password = PasswordField('密码:', validators=[DataRequired(), Length(1, 64)]) remember_me = BooleanField('记住密码', validators=[Optional()])@app.route('/login',methods=['GET','POST'])def login(): form = LoginForm() if form.validate_on_submit():  username = form.username.data  password = form.password.data  result = user_dal.User_Dal.login_auth(username,password)  model=result[1]  if result[0]['isAuth']:   login_user(model)   print('登陆成功')   print(current_user.username) #登录成功之后可以用current_user来取该用户的其他属性,这些属性都是sql语句查来并赋值给对象的。   return redirect('/t')  else:   print('登陆失败')   return render_template('login.html',formid='loginForm',action='/login',method='post',form=form) return render_template('login.html',formid='loginForm',action='/login',method='post',form=form)'''登录函数,首先实例化form对象然后通过form对象验证post接收到的数据格式是否正确然后通过login_auth函数,用username与password向数据库查询这个用户,并将状态码以及对象返回判断状态码,如果正确则将对象传入login_user中,然后就可以跳转到正确页面了'''@login_manager.user_loaderdef load_user(id): return user_dal.User_Dal.load_user_byid(id)'''load_user是一个flask_login的回调函数,在登陆之后,每访问一个带Login_required装饰的视图函数就要执行一次,该函数返回一个用户对象,通过id来用sql语句查到的用户数据,然后实例化一个对象,并返回。'''#登陆成功跳转的视图函数@app.route('/t')@login_requireddef hello_world(): print('登录跳转') return 'Hello World!'#随便写的另一个视图函数@app.route('/b')@login_requireddef hello(): print('视图函数b') return 'Hello b!'if __name__ == '__main__': app.run()

简单总结一下:

通过flask的form表单验证数据格式
然后通过用户名密码从数据库取用户对象,将sql执行结果赋值给一个实例化的对象
将这个对象传给login_user,
然后成功跳转。
注意要写一个load_user回调函数吗,返回的是通过id取到的数据库并实例化的对象的用户对象。
这个回调函数每次访问带login_required装饰器的视图函数都会被执行。
还有一个就是current_user相当于就是实例化的用户对象,可以取用户的其他属性,注意,其他属性仅限于sql语句查到的字段并添加给实例化对象的属性。

代码比较简单,只是为了实现功能,敬请谅解,如有错误欢迎指出。

更多关于Python相关内容可查看本站专题:《Python入门与进阶经典教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Sanic框架蓝图用法实例分析
    下一条:
    Flask框架各种常见装饰器示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    • 2025-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客