在前面我们分析了接口的设计,那么我们现在做接口的开发。

我们先去设计下pydantic用户参数的校验

from pydantic import BaseModel
from typing import Optional class UserBase(BaseModel):
username: str class UserCreate(UserBase):
"""
请求模型验证:
username:
password:
"""
password: str
role: int
jobnum: Optional[int] = None
studentnum: Optional[int] = None
sex: str = "男"
age: int

接着,我们去设计对应的crud,操作对应的数据库。

from sqlalchemy.orm import Session
from models.models import *
from models.schemas import *
def get_user(db: Session, user_id: int):
return db.query(User).filter(User.id == user_id,User.status==False).first()
# 新建用户
def db_create_user(db: Session, user: UserCreate):
roles = db.query(Role).filter(Role.name == user.role).first()
db_user = User(**user.dict())
db_user.role=roles.id
db.add(db_user)
db.commit() # 提交保存到数据库中
db.refresh(db_user) # 刷新
return db_user def get_user_username(db: Session, username: str):
return db.query(User).filter(User.username == username,User.status==False).first()

接下来,我们看下注册接口的逻辑

1.校验参数是否合规
2.查询用户名是否存在
3.密码加密
4.保存到数据库

我们根据我们的逻辑去开发我们的接口。

from fastapi import APIRouter, Request
from fastapi import Depends, HTTPException, Header
from models.crud import *
from models.get_db import get_db
from jose import JWTError, jwt
from passlib.context import CryptContext
from config import *
from common.jsontools import *
from common.logs import logger
usersRouter = APIRouter()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password):
return pwd_context.hash(password)
# 新建用户
@usersRouter.post("/create", tags=["users"])
def create_user(user: UserCreate, db: Session = Depends(get_db)): logger.info("创建用户")
if len(user.username)<8 or len(user.username)>16:
return reponse(code=100106,message="用户名长度应该是8-16位",data="")
if user.age<18:
return reponse(code=100103, message="年纪大小不符合", data="")
if (user.role == "学生" and user.studentnum is None) or (user.role == "教师" and user.jobnum is None) or (
user.role not in ["教师", '学生']):
return reponse(code=100102, message="身份和对应号不匹配", data="")
db_crest = get_user_username(db, user.username)
if db_crest:
return reponse(code=100104, message="用户名重复", data="")
try:
user.password = get_password_hash(user.password)
except Exception as e:
logger.exception(e)
return reponse(code=100105, data="", message="密码加密失败")
try:
user=db_create_user(db=db, user=user)
logger.success("创建用户成功")
return reponse(code=200,data={'user':user.username},message="success")
except Exception as e:
logger.exception(e)
return reponse(code=100101, data="", message="注册失败")

在启动的时候,我们需要在main.py下注册对应的路由。

from fastapi import FastAPI
from routers.user import usersRouter
app = FastAPI()
app.include_router(usersRouter, prefix="/user", tags=['users'])

然后对应的启动的

这样我们就完成了注册的接口的开发。这里的知识点用到了jose,passlib,这里如果不太熟悉,可以查看FastAPI 学习之路(三十)使用(哈希)密码和 JWT Bearer 令牌的 OAuth2

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

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

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

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

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

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

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

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

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

  5. FastAPI(六十七)实战开发《在线课程学习系统》接口开发--用户登陆接口开发

    接上一篇文章FastAPI(六十六)实战开发<在线课程学习系统>接口开发--用户注册接口开发.这次我们分享实际开发--用户登陆接口开发. 我们先来梳理下逻辑 1.查询用户是否存在2.校验密 ...

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. laravel 分页支持搜索功能

  2. java多线程中常用指令

    ------------恢复内容开始------------ 一.写在前面 好久没写博客了,这不快毕业了,应该会重新开始更新博客了.这次主要介绍查看线程状态等一系列常见指令,包括有jps.vmstat ...

  3. GO语言基础(结构+语法+类型+变量)

    GO语言基础(结构+语法+类型+变量) Go语言结构 Go语言语法 Go语言类型 Go语言变量       Go 语言结构 Go 语言的基础组成有以下几个部分: 包声明 引入包 函数 变量 语句 &a ...

  4. MySQL报错 SQL ERROR:1064 ,SQLState:42000

    使用mysql新增数据时报错,具体信息如图所示: 错误原因: 所建的表中 表名或字段名与数据库关键字冲突 解决办法 可以根据报错信息,查看错误的具体位置,找到数据库中对应的字段,查询是否与关键字(不分 ...

  5. 用strace处理程序异常挂死情况

    1. 环境: ubuntu 系统 + strace + vim 2.编写挂死程序:(参考博客) #include <stdio.h> #include <sys/types.h> ...

  6. 开发中常用的几种 Content-Type

    开发中常用的几种 Content-Type application/x-www-form-urlencoded 浏览器的原生 form 表单,如果不设置,那么最终就会以 application/x-w ...

  7. java反射 java动态代理和cglib动态代理的区别

    java反射      https://blog.csdn.net/f2764052703/article/details/89311013 java 动态代理   https://blog.csdn ...

  8. springboot user guide hand book

    手册: https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/html/getting-started-first-appli ...

  9. 如何确保消息正确地发送至 RabbitMQ? 如何确保消息接收方消费了消息?

    发送方确认模式 将信道设置成 confirm 模式(发送方确认模式),则所有在信道上发布的消息都 会被指派一个唯一的 ID. 一旦消息被投递到目的队列后,或者消息被写入磁盘后(可持久化的消息),信 道 ...

  10. 为什么WAIT必须在同步块中

    我们知道java的Object有wait和notify方法,如果要使用wait和notify的话,那么必须在synchronized块中,否则会抛出IllegalMonitorStateExcepti ...