1钩子函数
flask中钩子函数相当于django中在请求前及请求后做什么的中间件。
钩子函数有before:请求之前被调用,不能写return一个具体值,可以写return None;多个before从上到下执行
after:请求之后被调用,多个after从下到上执行;程序不抛异常/不出错的情况下,才会被调用
teardown:无论出错否,都会被执行
before_first:第一次请求才会调用,后面不会被调用。
from flask import Flask
app = Flask(__name__)
第一次调用时,才会被执行
@app.before_first_request
def before_first():
print('before_first')
@app.before_request
def before():
print('before request')
@app.before_request
def before1():
print('before request1')
@app.route('/index/')
def index():
return 'index'
程序不抛异常/不出错的情况下,才会被调用
@app.after_request
def after(response):
print('after request')
return response
@app.after_request
def after1(response):
print('after request1')
return response
无论如何都会执行
@app.teardown_request
def teardown(exception):
print('teardown request')
if __name__ == '__main__':
app.run()
最后输出为before_first;before request;before request1;after request1;after request;teardown request
2连接数据库
用钩子函数分步对数据库进行操作。
在flask框架中;如果在函数中声明了一个局部变量需要在另一个函数中使用;就需要引入g对象,先导入g;然后在局部变量处给g添加属性并赋值。在使用的地方以g对象.属性的方式使用。
from flask import Flask, request, g
import pymysql
app = Flask(__name__)
@app.before_request
def before():
# 连接数据库
con = pymysql.connect(host='127.0.0.1', port=3306, password='123456',
user='root', database='flask8')
# 创建游标
cursor = con.cursor()
# g对象;添加属性并赋值(g只存活于当前这个请求与响应之间)
g.con = con
g.cursor = cursor
@app.route('/sel_stu/', methods=['GET'])
def sel_stu():
if request.method == 'GET':
# 查询所有学生的信息
sql = 'select * from studnet;'
g.cursor.execute(sql)
data = g.cursor.fetchall()
print(data)
return '查询成功'
@app.teardown_request
def teardown():
g.con.close()
if __name__ == '__main__':
app.run(debug=True)
3邮件发送
3.1不用蓝图拆分发送邮件
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config["MAIL_SERVER"] = "smtp.163.com"
app.config["MAIL_PORT"] = 465 # 设置邮箱端口为465,默认为25,
由于阿里云禁止了25端口,所以需要修改
app.config["MAIL_USE_SSL"] = True # 163邮箱需要开启SSL
app.config["MAIL_USERNAME"] = "wanghaifei36@163.com"
app.config["MAIL_PASSWORD"] = "wanghai135588"
mail = Mail(app)
@app.route("/send_mail")
def send_mail():
"""
发送邮件, sender为发送者邮箱, recipients为接受者邮箱
"""
message = Message("测试邮件标题122",
sender=app.config["MAIL_USERNAME"],
recipients=["779598160@qq.com"])
message.body = "测试邮件的内容122"
send_email(message)
return "发送成功"
def send_email(msg):
mail.send(msg)
if __name__ == "__main__":
app.run(port=8080)
3.2用蓝图拆分发送邮件
manage.py中配置
from flask import Flask
from flask_script import Manager
from ema.views import mail, bluep
app = Flask(__name__)
app.config["MAIL_SERVER"] = "smtp.163.com"
# 设置邮箱端口为465,默认为25,由于阿里云禁止了25端口,所以需要修改
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True # 163邮箱需要开启SSL
app.config["MAIL_USERNAME"] = "huyifi@163.com"
app.config["MAIL_PASSWORD"] = "1qaz2wsx"
mail.init_app(app)
app.register_blueprint(blueprint=bluep, url_prefix='/ema')
manage = Manager(app=app)
if __name__ == '__main__':
manage.run()
视图函数views.py中文件配置
from flask_mail import Mail, Message
from flask import Blueprint
bluep = Blueprint('ema', __name__)
mail = Mail()
邮件发送
@bluep.route('/send_mail/')
def send_mail():
"""
发送邮件, sender为发送者邮箱, recipients为接受者邮箱
"""
message = Message('测试邮件标题', sender='huyifi@163.com',
recipients=['1501031048@qq.com'])
message.body = '测试邮件内容'
send_email(message)
return '邮件发送成功'
def send_email(msg):
mail.send(msg)
网友评论