qrcode_be/lib/db.py
2019-12-09 09:48:07 +08:00

120 lines
2.8 KiB
Python

from pymongo import MongoClient
from bson import ObjectId, json_util
# 主环境
setting = 'test'
# 获取数据集
def col(arg: str = None):
conn = MongoClient('mongodb://yingbo:623910ert@localhost:12236/yingbo')
param = None
if arg:
param = arg
else:
param = setting
if param == 'test':
return conn.yingbo.test
elif param == 'order':
return conn.yingbo.order
elif param == 'cache':
return conn.yingbo.cache
elif param == 'code':
return conn.yingbo.code
# 查找该用户所有信息
def findUser(openid):
arr = []
for i in col('code').find({'openId': openid}):
arr.append(i)
return json_util.dumps(arr)
# 查找该二维码所有信息
def findCode(id):
arr = []
try:
for i in col('code').find({"_id" : ObjectId(id)}):
arr.append(i)
except Exception as e:
# id不合法
return False
if(len(arr) == 0):
# 查询无结果
return False
return json_util.dumps(arr)
# 删除该二维码
def delCode(id):
try:
col('code').remove({"_id" : ObjectId(id)})
except Exception as e:
# id不合法
return False
return {'errcode': 200, 'errmsg': 'ok'}
# 用户上传进入缓存表
def insertOrderCache(data):
try:
col('cache').insert_one(data)
except Exception as e:
# 失败
return False
return True
# 用户付款回调 从缓存写进正式表
def cache2Test(out_trade_no,payjs_order_id):
try:
# 取出缓存表数据
cache = col('cache').find_one({"out_trade_no" : out_trade_no})
# 删除缓存表数据
col('cache').remove({"out_trade_no" : out_trade_no},1)
except Exception as e:
# 失败
return False
# 判断有没有,去重逻辑
if cache:
# 向原始数据中添加支付识别码
cache['payjs_order_id'] = payjs_order_id
# 插入到正式表
res = col().insert_one(cache)
# 返回插入的正式表id
inserted_id = res.inserted_id
# 放进order表建立 out_trade_no 到 objectId的 映射
try:
col('order').insert_one({'out_trade_no': out_trade_no, 'inserted_id': inserted_id})
except Exception as e:
# 失败
return False
return True
else:
return True
# 小程序端查询支付结果
def findOrder(out_trade_no):
arr = []
try:
for i in col('order').find({"out_trade_no" : out_trade_no}):
arr.append(i)
except Exception as e:
# 失败
return False
if(len(arr) == 0):
# 查询无结果
return False
else:
# 删除order中的记录
try:
col('order').remove({"out_trade_no" : out_trade_no})
except Exception as e:
# 失败
return False
return json_util.dumps(arr[0]['inserted_id'])
# 用户上传进入主表
def insertCode(data):
try:
res = col('code').insert_one(data)
inserted_id = res.inserted_id
except Exception as e:
# 失败
return False
return json_util.dumps(inserted_id)