user.py
# 用户模块
from flask import Flask, jsonify, request, Blueprint, session
import re
# 导入类试图
from flask.views import MethodView
# 导入数据库
from database import db,r
from utils import SendEmail,get_code,save_code,is_vaild_email,make_password,save_session_code
from sqlalchemy import text
# 导入随机
import random
# 导入图片绘制
from PIL import Image,ImageDraw
# 导入文件流
import io
# 导入flask输出组件
from flask import make_response
# 实例化蓝图对象
user_view = Blueprint('user_view',__name__)
# 图像验证码
class ImageCodeApi(MethodView):
def get(self):
# 画布
img_size = (120,30)
# 定义图像配置
image = Image.new('RGB',img_size,'white')
# 定义画笔
draw = ImageDraw.Draw(image,'RGB')
# 定义图像内容
source = '1234567890abcdefghijklmnopqrstuvwxyz'
# 字符串容器
code_str= ''
for i in range(4):
# 获取元素下标
index = random.randrange(len(source))
random_str = source[index]
# 绘制
draw.text((i*30+10,20),random_str,'black')
code_str += random_str
# 文件流操作
buf = io.BytesIO()
# 存储至内存
image.save(buf,'jpeg')
#定制化返回值
response = make_response(buf.getvalue())
#设置请求头
response.headers['Content-Type'] = 'image/jpeg'
return response
user_view.add_url_rule('/imagecode/',view_func=ImageCodeApi.as_view('imagecode'))
主路由app.py
# encoding: utf-8
import json
from flask import Flask, jsonify, request
from flask_cors import CORS
from database import db,r
from flask.views import MethodView
from sqlalchemy import text
from config import *
# 导入蓝图模块
from user import user_view
# 实例化flask对象
app = Flask(__name__)
# 配置转码
app.config['JSON_AS_ASCII'] = False
# 配置跨越
CORS(app, cors_allowed_origins="*")
# 配置mysql数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}:{}/{}'.format(mysql_user,mysql_password,mysql_host,mysql_port,mysql_db)
# 自动提交sql请求
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# 注册蓝图
app.register_blueprint(user_view)
# 设置flask内部session密钥,加密
app.config['SECRET_KEY'] = 'luckyletop'
# 初始化操作
db.init_app(app)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
标签:__,Flask,app,mysql,验证码,flask,user,图像,import
From: https://www.cnblogs.com/luckyletop/p/18583985