qrcode_be/lib/allFunction.py
2021-01-04 10:09:17 +08:00

108 lines
3.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
import json
import os
import qrcode
from db import findUser, delCode, insertCode
from login import getOpenid
from utils import checkData
from io import BytesIO
# 当前文件地址
basedir = os.path.abspath(os.path.dirname(__file__))
# js文件目录地址
datadir = os.path.join(basedir, '../data')
# 主函数
# 处理登录操作 debug完成
def manageLogin(request, is_mine):
# 获取openid
res = getOpenid(request.form['code'], is_mine)
if res['errcode'] == 200: # 获取成功返回用户信息
return {'userInfo': findUser(res['errmsg']['openid']), 'openid': res['errmsg']['openid'], 'errcode': 200}
else: # 获取失败返回失败信息
return res
# 小程序刷新用户信息 debug完成
def flash(request):
# 已知openId只包含-、_、数字和字母且长度为28位使用正则
openId = str(request.form['openId'])
if(len(openId) == 28): # 长度校验
pattern = re.compile(r'[^\w-]')
if(pattern.search(openId)): # 内容校验
return False
else:
# 返回用户信息
return {'userInfo': findUser(openId), 'errcode': 200}
else:
return False # 参数不全或者没通过校验
# 用户删除二维码 debug完成
def delQR(request):
# 已知openId只包含-、_、数字和字母且长度为28位使用正则
codeId = str(request.form['id'])
if(len(codeId) == 24): # 长度校验
if(codeId.isalnum()): # 内容校验
# 返回code信息
res = delCode(codeId)
if res:
filename = '{0}.js'.format(codeId)
path = os.path.join(datadir, filename)
if os.path.exists(path):
os.remove(path)
return res
else:
return False
else:
return False
else:
return False
# 用户上传二维码
def addQR(request):
# josn化应该能当dist用
dataCache = json.loads(request.form['data'])
# 校验所有用户上传的内容
data = checkData(dataCache)
if data:
res = insertCode(data)
if res:
id = str(data.get('_id'))
# 去除里边的id
data.pop('_id')
try:
filename = '{0}.js'.format(id)
path = os.path.join(datadir, filename) # 将信息写入文件
f = open(path, 'w', encoding="utf-8")
f.write('{0}{1}'.format('var data = ', data))
f.close()
except IOError:
return False
return {'errcode': 200, 'id': id}
else:
return False
else:
return False
def genQR(text):
# 空内容拦截
if not text:
return False
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=2
)
# 传入数据
qr.add_data(text)
qr.make(fit=True)
# 生成二维码
im = qr.make_image()
img = BytesIO()
# 将图片放图片流里面
im.save(img, format='PNG')
# 返回图片流
img = img.getvalue()
return img