接上一篇文章FastAPI(六十六)实战开发《在线课程学习系统》接口开发--用户注册接口开发。这次我们分享实际开发--用户登陆接口开发。

我们先来梳理下逻辑

1.查询用户是否存在2.校验密码是否正确3.密码校验失败记录失败次数4.失败次数大于10次,当天不能登陆5.密码校验通过产生对应的token返回

接着我们去设计pydantic,用于校验用户登陆

class UserLogin(UserBase):
password: str

  

这里我们继承的是之前的UserBase。

对应操作数据库的curd我们用之前注册的时候使用的get_user_username即可。

我们把密码输入失败和token放在redis中,那么redis对应的配置。

config.py配置
redishost='127.0.0.1'
redisport='6379'
redisdb=0

     我们在main.py增加配置

from fastapi import FastAPI
from aioredis import create_redis_pool, Redis
from routers.user import usersRouter
from routers.websoocket import socketRouter
from routers.file import fileRouter
from config import *
app = FastAPI()
async def get_redis_pool() -> Redis:
redis = await create_redis_pool(f"redis://:@"+redishost+":"+redisport+"/"+redisdb+"?encoding=utf-8")
return redis @app.on_event("startup")
async def startup_event():
app.state.redis = await get_redis_pool() @app.on_event("shutdown")
async def shutdown_event():
app.state.redis.close()
await app.state.redis.wait_closed()

  我们把产生token的配置也一并配置进去

#config.py
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

  那么产生token的代码如何实现呢。

from jose import JWTError, jwt
#routers/user.py
def create_access_token(data: dict):
to_encode = data.copy()
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

  接下来我们就是去根据逻辑去实现最后的代码了。

@usersRouter.post("/login", response_model=UsersToken)
async def login(request: Request, user: UserCreate, db: Session = Depends(get_db)):
db_crest = get_user_username(db, user.username)
if not db_crest:
logger.info("login:"+user.username+"不存在")
return reponse(code=100205,message='用户不存在',data="")
verifypassowrd = verify_password(user.password, db_crest.password)
if verifypassowrd:
useris = await request.app.state.redis.get(user.username)
if not useris:
try:
token = create_access_token(data={"sub": user.username})
except Exception as e:
logger.exception(e)
return reponse(code=100203,message='产生token失败',data='')
request.app.state.redis.set(user.username, token, expire=ACCESS_TOKEN_EXPIRE_MINUTES * 60)
return reponse(code=200,message='成功',data={"token":token})
return reponse(code=100202,message='重复登陆',data='')
else:
result=await request.app.state.redis.hgetall(user.username+"_password", encoding='utf8')
if not result:
times = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
request.app.state.redis.hmset_dict(user.username+"_password",num=0,time=times)
else:
errornum=int(result['num'])
numtime=(datetime.now() - datetime.strptime(result['time'],'%Y-%m-%d %H:%M:%S')).seconds / 60
if errornum<10 and numtime<30:
#更新错误次数
errornum += 1
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum)
return reponse(code=100206,data='',message='密码错误')
elif errornum<10 and numtime>30:
#次数置于1,时间设置现在时间
errornum=1
times = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum,time=times)
return reponse(code=100206,data='',message='密码错误')
elif errornum>10 and numtime<30:
#次数设置成最大,返回
errornum+=1
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum)
return reponse(code=100204,message='输入密码错误次数过多,账号暂时锁定,请30min再来登录',data='')
else:
errornum = 1
times = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum, time=times)
return reponse(code=100206, data='', message='密码错误')

  

我们按照最后的代码逻辑实现去完成。

一个完整的登陆接口就实现完毕了。

FastAPI(六十七)实战开发《在线课程学习系统》接口开发--用户登陆接口开发的更多相关文章

  1. FastAPI(六十八)实战开发《在线课程学习系统》接口开发--用户 个人信息接口开发

    在之前的文章:FastAPI(六十七)实战开发<在线课程学习系统>接口开发--用户登陆接口开发,今天实战:用户 个人信息接口开发. 在开发个人信息接口的时候,我们要注意了,因为我们不一样的 ...

  2. FastAPI(六十三)实战开发《在线课程学习系统》梳理系统需要接口

    针对上一篇FastAPI(六十二)实战开发<在线课程学习系统>需求分析需求的功能,我们对需要的接口进行梳理,大概的规划出来现有的接口,作为我们第一版的接口的设计出版,然后我们根据设计的接口 ...

  3. FastAPI(六十二)实战开发《在线课程学习系统》需求分析

    前言 基础的分享我们已经分享了六十篇,那么我们这次分享开始将用一系列的文章分享实战课程.我们分享的系统是在线学习系统.我们会分成不同的模块进行分享.我们的目的是带着大家去用fastapi去实战一次,开 ...

  4. FastAPI(六十九)实战开发《在线课程学习系统》接口开发--修改密码

    之前我们分享了FastAPI(六十八)实战开发<在线课程学习系统>接口开发--用户 个人信息接口开发.这次我们去分享实战开发<在线课程学习系统>接口开发--修改密码 我们梳理一 ...

  5. FastAPI(七十)实战开发《在线课程学习系统》接口开发--留言功能开发

    在之前的文章:FastAPI(六十九)实战开发<在线课程学习系统>接口开发--修改密码,这次分享留言功能开发 我们能梳理下对应的逻辑 1.校验用户是否登录 2.校验留言的用户是否存在 3. ...

  6. FastAPI(七十四)实战开发《在线课程学习系统》接口开发-- 删除留言

    之前文章FastAPI(七十三)实战开发<在线课程学习系统>接口开发-- 回复留言,那么我们这次分享删除留言接口的开发 可以对留言进行删除,这里的删除,我们使用的是逻辑的删除,不是物理删除 ...

  7. FastAPI(七十三)实战开发《在线课程学习系统》接口开发-- 回复留言

    之前文章分享FastAPI(七十二)实战开发<在线课程学习系统>接口开发-- 留言列表开发,这次我们分享如何回复留言 按照惯例,我们还是去分析这里面的逻辑. 1.判断用户是否登录 2.用户 ...

  8. FastAPI(七十二)实战开发《在线课程学习系统》接口开发-- 留言列表开发

    之前我们分享了FastAPI(七十一)实战开发<在线课程学习系统>接口开发-- 查看留言,这次我们分享留言列表开发. 列表获取,也需要登录,根据登录用户来获取对应的留言.逻辑梳理如下. 1 ...

  9. FastAPI(七十一)实战开发《在线课程学习系统》接口开发-- 查看留言

    之前FastAPI(七十)实战开发<在线课程学习系统>接口开发--留言功能开发分享了留言开发,这次我们分享查看留言 梳理这里的逻辑,这个接口要依赖登录. 1.判断用户是否登录 2.判断对应 ...

随机推荐

  1. think php 上下架修改+jq静态批量删除+ajax删除+全选

    视图代码: <!doctype html> <html lang="en"> <head> <meta charset="UTF ...

  2. 理解并手写 apply() 函数

    apply()函数,在功能上类似于call(),只是传递参数的格式有所不同. dog.eat.call(cat, '鱼', '肉'); dog.eat.apply(cat, ['鱼', '肉']); ...

  3. .NET 7 预览版2 的亮点之 NativeAOT 正式合并入 .NET 主线

    .NET 中备受追捧和期待已久的功能NativeAOT终于出现在本周的.NET 7 预览版2中,该项目的工作仍在继续,该版本将 NativeAOT 从实验性的 dotnet/runtimelab re ...

  4. 关于Stream系列实战

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  5. k8s学习笔记一(搭建&部署helloworld应用)

    kubernetes 目录 kubernetes 虚拟机创建三个节点 k8s install 部署hello world 应用 issue 汇总 node 一直处理NotReady状态 重启系统后虚拟 ...

  6. kubernetes如何强制删除namespace

    K8S如何强制删除namespace 先运行kubectl get namespace ingress-nginx -o json > nginx.json,拿到当前namespace描述,然后 ...

  7. python prettytable 模块

    #coding:utf-8 # qianxiao996精心制作 from prettytable import PrettyTable x = PrettyTable(["名称", ...

  8. 学习SpringMVC必知必会(2)~走近Spring MVC

    一.Spring 基本介绍 1.什么是 Spring MVC? SpringMVC 是 Spring-Frame 框架的子集(Spring-Frame包含了Spring MVC), MVC 框架,(类 ...

  9. EasyUI 之datagrid 使用 【DataGrid属性解释】

    可选的参数 DataGrid 属性 覆写了 $.fn.datagrid.defaults. 参数名 类型 描述 默认值 title string Datagrid面板的标题 null iconCls ...

  10. Session Cookie Token Json-Web-Token

    什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证明"你是你自己"(比如:你每天上下班打卡,都需要通过指纹打卡,当你的指纹和系统里录入的指纹相匹配时,就 ...