Flask基础学习3

news/2025/2/21 18:24:40/

参考视频:41-【实战】答案列表的渲染_哔哩哔哩_bilibili


 flask 实现发送短信功能

pip install flask-mail # 安装依赖

 我这里用登录的网易邮箱获取的授权码(登录QQ邮箱的授权码总是断开收不到邮件),

# config
# config mail
MAIL_SERVER = 'smtp.163.com'
MAIL_USE_SSL = True
MAIL_PORT = 465
MAIL_USERNAME = 'xxx@163.com'
MAIL_PASSWORD='xxx'
MAIL_DEFAULT_SENDER  = 'xxx@163.com'
@bp.route('/mail/test')
def mail_test():message = Message(subject='mail test',recipients=['xxx@qq.com'],body='xxx')mail.send(message)

运行结果:

邮箱发送验证功能实现

@bp.route('/captcha/email')
def get_mail_cptcha():email = request.args.get('email')source= string.digits*4cap = random.sample(source,4)cap  = ''.join(cap)message = Message(subject='菜鸟学习测试', recipients=[email], body='你的验证码是:{}'.format(cap))mail.send(message)email_capt = EmailCaptchModel(email=email,captcha=cap)db.session.add(email_capt)db.session.commit()return jsonify({'code':200,'message':'','data':None})

查看DB数据

注册表单验证实现:

# blueprints/forms.py
import wtforms
from wtforms.validators import Email,Length,EqualTo
from models import UserModel,EmailCaptchModelclass RegisterForm(wtforms.Form):email = wtforms.StringField(validators=[Email(message="邮箱格式错误!")])captcha = wtforms.StringField(validators=[Length(min=4,max=4,message="验证码格式错误!")])username = wtforms.StringField(validators=[Length(min=3,max=20,message="用户名格式错误!")])password = wtforms.StringField(validators=[Length(min=3,max=20,message="密码长度为4-20位!")])password_confirm = wtforms.StringField(validators=[EqualTo('password',message="两次输入的错误不一致!")])def validate_email(self, field):email = field.datauser = UserModel.query.filter_by(email=email).first()if user:raise wtforms.ValidationError(message='该邮箱已经被注册!')def validate_captcha(self,field):captcha = field.dataemail = self.email.datacaptcha_model = EmailCaptchModel.query.filter_by(email=email,captcha=captcha).first()if not captcha_model:print('邮箱或验证码格式错误!')# raise wtforms.ValidationError(message='邮箱或验证码格式错误!')# else:#     db.session.delete(captcha_model)#     db.session.commit()

 注册功能后端的实现

# blueprints/auth.py
@bp.route('/register',methods = ['POST','GET'])
def register():if request.method == 'GET':return render_template('regist.html')form  = RegisterForm(request.form)if form.validate():email = form.email.datausername= form.username.datapassword = form.password.datauser= UserModel(email=email,username=username,password=generate_password_hash(password))db.session.add(user)db.session.commit()return redirect(url_for('auth.login'))else:print(form.data)print(form.errors)return redirect(url_for('auth.register'))

运行结果:

 登录功能后端的实现,并将session信息加密保存到cookie中

# forms.py
class LoginForm(wtforms.Form):email = wtforms.StringField(validators=[Email(message="邮箱格式错误!")])print(wtforms.validators.Email)password = wtforms.StringField(validators=[Length(min=4, max=20, message="密码长度为4-20位!")])# auth.py
@bp.route('/login',methods = ['POST','GET'])
def login():if request.method == 'GET':return render_template('login.html')form = LoginForm(request.form)print(form.data)if form.validate():email = form.email.datapassword = form.password.datauser = UserModel.query.filter_by(email=email).first()if not user:print('邮箱在数据库中不存在')return redirect(url_for('auth.login'))if check_password_hash(user.password,password):# cookie 存在浏览器上# flsk的session 是加密存在在cookiesession['user.id'] = user.idreturn redirect(url_for('auth.index'))else:print('密码错误')return redirect(url_for('auth.login'))else:print(form.errors)return redirect(url_for('auth.login'))

注意: 配置session信息时要配置自定义密钥,否则会报错

# 配置session
SECRET_KEY = 'DSAFSDFASFASDFADFSDSASFD' # 无要求,自定义

两个钩子的运用及实现

# from flask import g
# 全局变量g
@login_required
def my_before_request():user_id = session.get('user_id')if user_id:user = UserModel.query.get(user_id)setattr(g,'user',user)else:setattr(g,'user',None)@app.context_processor
def my_context_processor():return {'user':g.user}

配置用户的登录名称显示及注销功能的实现

{% if user %}<li><a href="#">{{ user.username }}</a></li><li><a href="{{ url_for('auth.logout') }}">注销</a></li>
{% else %}<li><a href="{{url_for('auth.login')}}">登录</a></li><li><a href="{{url_for('auth.register')}}">注册</a></li>
{% endif %}
@bp.route('/logout')
def logout():session.clear()return render_template('index.html')

发布问答后端接口的实现

# model.py
class QuestionModel(db.Model):__tablename__ = 'question'id = db.Column(db.Integer,primary_key=True,autoincrement=True)title = db.Column(db.String(1000),nullable=False)content = db.Column(db.Text,nullable=False)create_time = db.Column(db.DateTime,default=datetime.now())author_id = db.Column(db.Integer,db.ForeignKey('user.id'))author = db.relationship(UserModel,backref = 'questions')# form 验证器
class QuestionForm(wtforms.Form):title = wtforms.StringField(validators=[Length(min=4, max=100, message="标题格式错误!")])context = wtforms.StringField(validators=[Length(min=3, max=200, message="内容格式错误")])
from flask import Blueprint,request,render_template
from .forms import QuestionForm
from decorators import login_required
from models import QuestionModel
from exts import db
bp=Blueprint('qa',__name__,url_prefix='/qa')@bp.route('/question',methods = ['POST','GET'])
def question():if request.method == 'GET':return render_template('question.html')else:form  =QuestionForm(request.form)print(form.data)if form.validate():title = form.title.datacontext = form.context.dataquestion = QuestionModel(title=title,content=context,author=g.user)db.session.add(question)db.session.commit()return render_template('index.html')else:print(form.errors)return render_template('question.html')

登录装饰器的实现,只有在登录后才可进行发布问答

# 自定义登录装饰器
from functools import wraps
from flask import g,redirect,url_for
def login_required(func):# 保留func的信息@wraps(func)def inner(*args,**kwargs):if g.user:return func(*args,**kwargs)else:return redirect(url_for('auth.login'))return inner# 配置装饰器
@login_required
def question()

问答列表首页功能实现:

@bp.route('/')
def index():# 根据创建时间倒序排列questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()return render_template('index.html',questions=questions)

发布问答详细的功能实现

@bp.route('/qa/detail/<qa_id>')
def qa_detail(qa_id):question=QuestionModel.query.get(qa_id)return render_template('detail.html',question=question)@bp.post('/answer/public')
@login_required
def public_answer():form = AnswerForm(request.form)if form.validate():content = form.context.dataquestion_id = form.question_id.dataanswer = AnswerModel(content=content,question_id=question_id,author_id=g.user.id)db.session.add(answer)db.session.commit()return redirect(url_for('qa.qa_detail',qa_id=question_id))else:print(form.errors)return redirect(url_for('qa.qa_detail', qa_id=request.form.get('question_id')))

搜索功能的实现

@bp.route('/search')
def search():q = request.args.get('q')# 搜索标题的关键字questions= QuestionModel.query.filter(QuestionModel.title.contains(q)).all()return render_template('index.html',questions=questions)

 okok


http://www.ppmy.cn/news/1362670.html

相关文章

基于SpringBoot+Apache ECharts的前后端分离外卖项目-苍穹外卖(十八)

数据展示 1. Apache ECharts1.1 介绍1.2 入门案例 2. 营业额统计2.1 需求分析和设计2.1.1 产品原型2.1.2 接口设计 2.2 代码开发2.2.1 VO设计2.2.2 Controller层2.2.3 Service层接口2.2.4 Service层实现类2.2.5 Mapper层 2.3 功能测试 3. 用户统计3.1 需求分析和设计3.1.1 产品…

2024最新可用免费天气预报API接口

天气API接口数据, 数据字段最全&#xff0c;免费&#xff0c;稳定的实况天气预报接口 5分钟左右更新一次&#xff0c;支持全国3000多个市区县, 包含基本天气信息、24小时逐小时天气、气象预警列表、湿度、能见度、气压、降雨量、紫外线、风力风向风速、日出日落、空气质量、pm2…

mysql数据库 - 统诉

1、DDL - 数据库操作 show databases; create database 数据库名 use 数据库名 select database() drop database 数据库名 2、DDL- 表操作 show tables; create table desc 表名 show create table 表名 alter table 表名 add/modify/change/rename drop table 表名 3、DML …

详解0.9寸OLED驱动开发(linux platform tree i2c 应用实例)

目录 概述 1 认识OLED 1.1 OLED简介 1.2 SSD1306介绍 1.3 0.9寸OLED模块介绍 1.4 i2c操作OLED时序 2 驱动代码实现 2.1 查看i2c总线下Device 2.2 OLED驱动接口 2.2.1 初始化函数 2.2.2 写指令函数 2.2.3 其他接口函数 2.3 完整驱动代码 3 编译 3.1 编写测试程序 …

matlab|计及源荷不确定性的综合能源生产单元运行调度与容量配置随机优化模型

目录 1 主要内容 1.1 风光场景聚类 1.2 主模型程序结果 1.3 随机模型和确定性模型对比 1.4 有无储气对比 1.5 煤价灵敏性分析 1.6 甲烷价格灵敏性分析 2 部分程序 3 下载链接 1 主要内容 本程序复现《计及源荷不确定性的综合能源生产单元运行调度与容量配置两阶段随机…

SpringBoot3整合Swagger3,访问出现404错误问题(未解决)

秉承着能用就用新的的理念&#xff0c;在JDK、SpringBoot、SpringCloud版本的兼容性下&#xff0c;选择了Java17、SpringBoot3.0.2整合Swagger3。 代码编译一切正常&#xff0c;Swagger的Bean也能加载&#xff0c;到了最后访问前端页面swagger-ui的时候出现404。 根据网上资料…

抖音数据挖掘软件|视频内容提取

针对用户获取抖音视频的需求&#xff0c;我们开发了一款功能强大的工具&#xff0c;旨在解决用户在获取抖音视频时需要逐个复制链接、下载的繁琐问题。我们希望用户能够通过简单的关键词搜索&#xff0c;实现自动批量抓取视频&#xff0c;并根据需要进行选择性批量下载。因此&a…

matlab simulink变压器温度仿真

1、内容简介 略 48-可以交流、咨询、答疑 2、内容说明 略 3、仿真分析 略 matlab simulink变压器温度仿真_哔哩哔哩_bilibili 4、参考论文 略 大型油浸风冷变压器绕组温度场分析_高原 基于顶层油温的变压器绕组热点温度计算改进模型_陈伟根 基于热电类比理论的油浸式电…