def post(self, request, id): try: # 尝试获取当前id对应的投票条目 polling_item = PollingItem.objects.get(id=id) except PollingItem.DoesNotExist: raise exceptions.NoSuchResource # 如果已报名成功则不允许修改信息 if polling_item.is_successful == True: raise exceptions.ArgumentError # 如果未上传头像图则不允许保存 if not PollingItemImages.objects.filter( polling_item=polling_item, does_exist=True, is_avatar=True): raise exceptions.PermissionDenied polling_item.city = '' polling_item.name = request.data['name'] polling_item.phone = request.data['phone'] polling_item.pub_date = datetime.now() polling_item.is_successful = True polling_item.save() # 为该选手推送模板消息 access_token = get_access_token() time_now = int(time.time()) # 获取其可用的formid formids = MemberFormId.objects.filter(is_available=True, timestamp__gt=time_now, member=polling_item.member) if formids: formid = formids[0] data = { "touser": polling_item.member.openid, "template_id": '5EShq2O4kDPDJSIX0du9LxaskidmA0iq09nB7w6dLf0', "page": 'pages/pollDetail/main?candidateId=' + id, "form_id": formid.formid, "data": { 'keyword1': { 'value': "遇见荆彩", }, 'keyword2': { 'value': request.data['name'], }, 'keyword3': { 'value': '您已报名成功,快去为自己拉票吧!', } }, } formid.is_available = False formid.save() push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) formid.is_available = False formid.save() response = { 'code': 0, 'error': '', } return Response(response)
def post(self, request): # 记录当前用户的formid(2个) password = request.data['password'] # post请求发送的密码 if password != 'Ien6Hvq9GXkXCkeiDJxryesGS7Tievcx': raise exceptions.RequestFailed client_ip = request.META['REMOTE_ADDR'] # if client_ip != "59.173.98.1": # 此为测试服务器的ip,只有测试服务器发送该请求可以返回数据 if client_ip != "47.105.166.254": raise exceptions.RequestFailed access_token = get_access_token() # 密钥 pc = PrpCrypt('JEwKENYmRMSEYbn87Do5qQNagVxGJshl') e = pc.encrypt(access_token) return Response(e)
def SendMessage(msg, polling_items): access_token = get_access_token() time_now = int(time.time()) today = datetime.now() year = today.strftime('%y') #今天的年份 month = today.strftime('%m') # 今天的月份 date = today.strftime('%d') # 今天的日期 for polling_item in polling_items: # 获取其可用的formid formids = MemberFormId.objects.filter(member=polling_item.member, is_available=True, timestamp__gt=time_now) if formids: formid = formids[0] data = { "touser": polling_item.member.openid, "template_id": 'Ntuj-5GgDQZEVMEPp9eBmbqbANmO_s-M204zzjKzE2c', "page": 'pages/luckyPerson/main', "form_id": formid.formid, "data": { 'keyword1': { 'value': msg, }, 'keyword2': { 'value': '抽奖啦!赶紧戳进来看看大奖名单', }, 'keyword3': { 'value': '武汉约跑社体育文化管理有限公司', }, 'keyword4': { 'value': '空顶帽+腰包+压缩腿套+髌骨带', }, 'keyword5': { 'value': '{}年{}月{}日'.format(year, month, date) } }, } push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) formid.is_available = False formid.save() else: print(polling_item.id + '通知失败,没有可用的fromid\n')
def get(self, request, id): try: # 尝试获取当前id对应的投票条目 polling_item = PollingItem.objects.get(id=id, is_successful=True) except PollingItem.DoesNotExist: raise exceptions.NoSuchResource # 尝试获取生成参数 if polling_item.two_bar_codes: response = { 'data': { 'two_bar_codes': str(polling_item.two_bar_codes) }, 'code': 0, 'error': '', } return Response(response) access_token = get_access_token() QRcode_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format( access_token) raw_data = { 'scene': id, 'page': 'pages/pollDetail/main', 'width': request.data.get('width', 430), 'auto_color': request.data.get('auto_color', False), 'line_color': request.data.get('line_color', { "r": 0, "g": 0, "b": 0 }), 'is_hyaline': request.data.get('is_hyaline', True), } data = json.dumps(raw_data) QRcode_request = requests.post(QRcode_url, data=data) img = 'media/polling/item/share/' + id + '.png' with open(img, 'wb') as f: f.write(QRcode_request.content) polling_item.two_bar_codes = str(img) polling_item.save() response = { 'data': { 'two_bar_codes': img }, 'code': 0, 'error': '', } return Response(response)
def RemindPollingAuto(): access_token = get_access_token() time_now = int(time.time()) today = datetime.now().date() begin = today + timedelta(-7) end = today + timedelta(-1) # 筛选七天内投过票的所有人 members = MemberPollingRecord.objects.filter( vote_date__range=(begin, end)).values('member').annotate(Count('id')) for member in members: id = member['member'] # 获取其可用的formid formids = MemberFormId.objects.filter(is_available=True, timestamp__gt=time_now, member=id) if formids: formid = formids[0] data = { "touser": formid.member.openid, "template_id": 'M-zLsu0x08j9kAhbseMPC1UvUO0sXZaM9ocEqWUwKJo', "page": 'pages/pollList/main?pollId=95bfcff3bd6849c895d065550fbc07b8', "form_id": formid.formid, "data": { 'keyword1': { 'value': "第二届中国最美女跑者", }, 'keyword2': { 'value': '您今日的投票机会已更新,快来为喜欢的女跑者投上一票吧!', }, 'keyword3': { 'value': '您喜欢的选手就快被反超了,来看看她的排名吧!', } }, } formid.is_available = False formid.save() push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) formid.is_available = False formid.save()
def readexecl(self, request, queryset): # 每次只允许更新一个文件 if queryset.count() != 1: return False delivery_record = queryset[0] filename = 'media/{}'.format(delivery_record.filename) sheet_index=0 table_header_row=0 # 打开excel文件读取数据 data = xlrd.open_workbook(filename) table = data.sheet_by_index(sheet_index) nrows = table.nrows nclos = table.ncols # 获取表头行的信息,为一个字典 header_row_data = table.row_values(table_header_row) # 将每行的信息放入一个字典,再将字典放入一个列表中 record_list = [] for rownum in range(1, nrows): rowdata = table.row_values(rownum) # 如果rowdata有值, if rowdata: dict = {} for j in [0, 1, 2, 3, 4, 5]: # 将excel中的数据分别设置成键值对的形式,放入字典,如‘标题’:‘name’; dict[header_row_data[j]] = rowdata[j] record_list.append(dict) access_token = get_access_token() amount = 0 failure = 0 remark = '' for record in record_list: try: out_trade_no = record['订单号'] order = Order.objects.get(out_trade_no=out_trade_no, order_status='has_paid') if order.address_id.phone != record['电话']: failure += 1 remark += record['订单号'] + '订单信息匹配有误 ' continue order.order_status = 'has_posted' order.express_type = record['快递公司'] order.express_num = str(record['运单号']) order.save() data = { "touser": order.member_id.openid, "template_id": '6-5tFGpGD9zV3_aAMgL6P9g5-LRnwNO4lrjnH474Z3c', "page": 'pages/me/main', "form_id": order.prepay_id, "data": { 'keyword1': { 'value': order.goods_id.name, }, 'keyword2': { 'value': '您的商品已发货,正向您飞速赶来,请注意查收哦!', }, 'keyword3': { 'value': order.express_num, }, 'keyword4': { 'value': order.express_type, } }, } push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) amount += 1 except: failure += 1 remark += record['订单号'] + '保存订单信息或发送消息通知失败 ' delivery_record.is_update = True delivery_record.amount = amount delivery_record.failure = failure delivery_record.remark = remark delivery_record.save() return 'ok'
def get(self, request, prepay_id): response = {'data': {}, 'code': 0, 'error': 'deal success'} try: # 获取个人信息 participation_info = ParticipationInfo.objects.get( member=request.user) except: response['error'] += ' 个人信息查询失败 ' try: # 获取参赛记录 record = CompetitionEventParticipationRecord.objects.get( member=request.user, prepay_id=prepay_id, pay_status=True) # 获取对应比赛信息 marathon_info = Marathon.objects.get(id=record.marathon_id) date = marathon_info.time.strftime("%Y-%m-%d %H:%M:%S") access_token = get_access_token() # 发送模板封装 data = { "touser": record.member.openid, "template_id": 'vkRjdubdEt-75wg11ThxMpLbevGQZr2Ul6iTZVVWT5Y', "page": 'pages/me/main', "form_id": record.prepay_id, "data": { 'keyword1': { 'value': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))), }, 'keyword2': { 'value': date, }, 'keyword3': { 'value': participation_info.name, }, 'keyword4': { 'value': marathon_info.place, } }, } push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) except: # 用户支付成功,由于微信回调出错导致付款状态未更新,进行下面更新 record = CompetitionEventParticipationRecord.objects.get( member=request.user, prepay_id=prepay_id) record.pay_status = True record.save() marathon_info = Marathon.objects.get(id=record.marathon_id) date = marathon_info.time.strftime("%Y-%m-%d %H:%M:%S") access_token = get_access_token() data = { "touser": record.member.openid, "template_id": 'vkRjdubdEt-75wg11ThxMpLbevGQZr2Ul6iTZVVWT5Y', "page": 'pages/me/main', "form_id": record.prepay_id, "data": { 'keyword1': { 'value': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))), }, 'keyword2': { 'value': date, }, 'keyword3': { 'value': participation_info.name, }, 'keyword4': { 'value': marathon_info.place, } }, } push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) response = {'data': {}, 'code': 0, 'error': '付款状态更新成功'} return Response(response)
def post(self, request, id): try: # 尝试获取当前id对应的投票条目 polling_item = PollingItem.objects.get(id=id) except PollingItem.DoesNotExist: raise exceptions.NoSuchResource # 如果已报名成功则不允许修改信息 if polling_item.is_successful == True: raise exceptions.ArgumentError # 如果未上传头像图则不允许保存 if not PollingItemImages.objects.filter( polling_item=polling_item, does_exist=True, is_avatar=True): raise exceptions.PermissionDenied # 核验短信验证码 verification_code = request.data.get('verification_code', '') if not (verification_code.isdigit() and len(verification_code) == 6): # 参数错误 raise exceptions.RequestFailed try: # 尝试查找当前用户的核验手机号记录 check_mobile = CheckMobile.objects.get(member=request.user) except CheckMobile.DoesNotExist: # 核验记录不存在 raise exceptions.RequestFailed if check_mobile.verification_code != int(verification_code): # 验证码与核验记录不匹配 raise exceptions.RequestFailed if check_mobile.has_expired: # 验证码超时 raise exceptions.RequestFailed # 把验证通过的手机号存入member表里 request.user.mobile = check_mobile.mobile request.user.save(update_fields=('mobile', )) # 删除之前的核验记录 CheckMobile.objects.filter(member=request.user).delete() # 所有验证都通过,开始存数据 city = request.data['cityName'] if city == '省直辖县级行政区划': city = request.data['countyName'] if city == '县': city = '重庆市' polling_item_city = PollingItemCity.objects.filter(name=city) if not polling_item_city: polling_item_city_dic = { 'name': city, 'polling_activity': polling_item.polling_activity, } polling_item_city = PollingItemCity(**polling_item_city_dic) polling_item_city.save() else: polling_item_city = polling_item_city[0] address = request.data['provinceName'] + ' ' + request.data['cityName'] + ' ' + \ request.data['countyName'] + ' ' + request.data['detailInfo'] latitude = float(request.data['latitude']) longitude = float(request.data['longitude']) coordinates = Point(longitude, latitude, srid=4326) polling_item.name = request.data['name'] polling_item.phone = request.data['phone'] polling_item.city = polling_item_city polling_item.address = address polling_item.pub_date = datetime.now() polling_item.is_successful = True polling_item.coordinates = coordinates polling_item.save() polling_item_city.number += 1 polling_item_city.save() # 为该选手推送模板消息 access_token = get_access_token() time_now = int(time.time()) # 获取其可用的formid formids = MemberFormId.objects.filter(is_available=True, timestamp__gt=time_now, member=polling_item.member) if formids: formid = formids[0] data = { "touser": polling_item.member.openid, "template_id": '5EShq2O4kDPDJSIX0du9LxaskidmA0iq09nB7w6dLf0', "page": 'pages/pollDetail/main?candidateId=' + id, "form_id": formid.formid, "data": { 'keyword1': { 'value': "第二届中国最美女跑者评选", }, 'keyword2': { 'value': request.data['name'], }, 'keyword3': { 'value': '您已报名成功,快来为自己拉票吧!\n添加约跑社客服微信,关注活动最新动态哦,微信号:yuepaosheyps', } }, } formid.is_available = False formid.save() push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format( access_token) requests.post(push_url, json=data, timeout=3) formid.is_available = False formid.save() response = { 'code': 0, 'error': '', } return Response(response)