def post(self): files = self.request.files.get('img', None) res = {'code': 0} if not files: res['code'] = 1 res['msg'] = '上传图片不能为空' logger.warning('[ERROR] %s' % '上传图片不能为空') return self.finish(res) if files[0]['content_type'] not in IMAGE_FORMAT: res['code'] = 1 res['msg'] = '上传图片格式有误' logger.warning('[ERROR] %s' % '上传图片格式有误') return self.finish(res) upload_path = os.path.join(BASE_DIR, 'static/upload') if not os.path.exists(upload_path): os.mkdir(upload_path) for file in files: with open(upload_path + '/' + file['filename'], 'wb') as up: up.write(file['body']) res['msg'] = '图片上传成功' logger.info('[SUCCESS] %s' % '图片上传成功') return self.finish(res)
def get(self): openid = self.get_argument('openid', None) discount_id = self.get_argument('discount_id', '0') logger.info('openid: %s' % openid) logger.info('discount_id: %s' % discount_id) sql = """ select openid, discount_id, discount, name, type, rule from wx_user_discount_rel as wudr inner join wx_discount as wd on wd.id = wudr.discount_id inner join wx_discount_type as wdt on wdt.id = wd.type_id where openid = '%s' and discount_id = %d and wudr.state = false """ % (openid, int(discount_id)) res = {'code': 0} conn = Postgres() data = conn.fetchone(sql) if data: res['msg'] = '扫码成功' res['data'] = data else: res['code'] = -1 res['msg'] = '该优惠券已失效,请勿重复扫码!' return self.finish(res)
def get_media_count(self): access_token = self.get_access_token() postUrl = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=%s" % access_token urlResp = request.urlopen(url=postUrl) urlResp = json.loads(urlResp.read().decode('utf-8')) if not urlResp.get('errcode'): logger.info('media_count获取成功') logger.info('media_count: %s' % urlResp) else: logger.error('media_count获取失败') logger.error('errcode: %s' % urlResp['errcode']) logger.error('errmsg: %s' % urlResp['errmsg'])
def get_media_list(self, type='image', offset=0, count=10): access_token = self.get_access_token() postUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s" % access_token postData = {'type': type, 'offset': offset, 'count': count} headers = {'content-type': 'application/json'} req = request.Request(url=postUrl, headers=headers, data=json.dumps(postData).encode('utf-8'), method='POST') urlResp = json.loads(request.urlopen(req).read().decode('utf-8')) if not urlResp.get('errcode'): logger.info('media_list获取成功') logger.info('media_list: %s' % urlResp) return urlResp else: logger.error('media_list获取失败') logger.error('errcode: %s' % urlResp['errcode']) logger.error('errmsg: %s' % urlResp['errmsg'])
def post(self): try: webData = self.request.body logger.info('接收信息: %s' % webData) recMsg = receive.parse_xml(webData) if isinstance(recMsg, receive.Msg): toUser = recMsg.FromUserName fromUser = recMsg.ToUserName # 文本信息处理 if recMsg.MsgType == 'text': content = "好的,密语君会尽快为您处理^_^" replyMsg = reply.TextMsg(toUser, fromUser, content) self.write(replyMsg.send()) # 图片信息处理 elif recMsg.MsgType == 'image': mediaId = recMsg.MediaId replyMsg = reply.ImageMsg(toUser, fromUser, mediaId) self.write(replyMsg.send()) elif recMsg.MsgType == 'event': # 关注公众号事件 if recMsg.Event == 'subscribe': content = '您好,欢迎关注密语君^_^\n更多优惠请留意粉丝福利!' replyMsg = reply.TextMsg(toUser, fromUser, content) self.write(replyMsg.send()) # 菜单点击事件 elif recMsg.Event == 'CLICK': eventKey = recMsg.EventKey print('点击事件:', eventKey) if eventKey == 'phone': content = '139 2829 0304' replyMsg = reply.TextMsg(toUser, fromUser, content) self.write(replyMsg.send()) elif eventKey == 'score_rule': content = """积分说明: 1. 每天登陆可领取5积分 2. 每使用一张优惠券可增加20积分 3. 积分可以兑换优惠券""" replyMsg = reply.TextMsg(toUser, fromUser, content) self.write(replyMsg.send()) else: self.write(reply.Msg().send()) except Exception as err: return err
def get(self): try: signature = self.get_argument('signature') timestamp = self.get_argument('timestamp') nonce = self.get_argument('nonce') echostr = self.get_argument('echostr') token = "LiJiaF" tmp = [token, timestamp, nonce] tmp.sort() tmp = "".join(tmp) hashcode = hashlib.sha1(tmp.encode('utf8')).hexdigest() if hashcode == signature: logger.info('微信公众号接入成功') self.write(echostr) else: logger.error('微信公众号接入失败') self.write('') except Exception as err: self.write(err)
def post(self): name = self.get_argument('name', '') res = {'code': 0} try: name_check = FiledsCheck(name, msg='分类名称', min_lenght=2, max_length=10) name_check.check_null() name_check.check_length() except FiledsError as msg: res['code'] = 1 res['msg'] = str(msg) logger.warning('[ERROR] %s' % str(msg)) return self.finish(res) try: sql = 'insert into article_class (name) values ("%s")' % name count = db.insert(sql) if count: logger.info('[SUCCESS] %s 添加成功' % name) res['msg'] = '添加成功!' else: raise MysqlError except MysqlError as e: logger.error('[ERROR] %s 添加失败' % name) res['code'] = 1 res['msg'] = '添加失败,请重新添加!' print(e) except Exception as e: logger.error('[ERROR] %s 添加失败' % name) res['code'] = 1 res['msg'] = '添加失败,请重新添加!' print(e) return self.finish(res)
def get_jsapi_ticket(self): jsapi_ticket = '' if not redis.exists('token:jsapi_ticket'): access_token = self.get_access_token() postUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi" % access_token urlResp = request.urlopen(postUrl) urlResp = json.loads(urlResp.read().decode('utf-8')) if not urlResp.get('errcode'): redis.set('token:jsapi_ticket', urlResp['ticket']) redis.expire('token:jsapi_ticket', 7000) jsapi_ticket = urlResp['ticket'] logger.info('jsapi_ticket获取成功') else: logger.error('jsapi_ticket获取失败') logger.error('errcode: %s' % urlResp['errcode']) logger.error('errmsg: %s' % urlResp['errmsg']) else: jsapi_ticket = redis.get('token:jsapi_ticket').decode('utf-8') logger.info('jsapi_ticket获取成功') return jsapi_ticket
def get_access_token(self): access_token = '' if not redis.exists('token:access_token'): postUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % ( APPID, APPSECRET) urlResp = request.urlopen(postUrl) urlResp = json.loads(urlResp.read().decode('utf-8')) if not urlResp.get('errcode'): redis.set('token:access_token', urlResp['access_token']) redis.expire('token:access_token', 7000) access_token = urlResp['access_token'] logger.info('access_token获取成功') else: logger.error('access_token获取失败') logger.error('errcode: %s' % urlResp['errcode']) logger.error('errmsg: %s' % urlResp['errmsg']) else: access_token = redis.get('token:access_token').decode('utf-8') logger.info('access_token获取成功') return access_token
def get(self): code = self.get_argument('code', None) logger.info('code: %s' % code) try: user_auth = UserAuth(APPID, APPSECRET, code) access_token, openid = user_auth.get_access_token() except Exception as e: return self.write(str(e)) # openid = 'oBGCb1GE38DXO03ebeY0MtnfJKmc' conn = Postgres() sql = """ select wd.id,name,type,discount,score,count,rule from wx_discount as wd inner join wx_discount_type as wdt on wd.type_id = wdt.id where state = true order by score desc, id desc """ data = conn.fetchall(sql) return self.render('discount.html', data=data, openid=openid)
def get(self): url = self.get_argument('fullUrl', None) jsapi_ticket = Basic().get_jsapi_ticket() logger.info('url:%s' % url) logger.info('jsapi_ticket:%s' % jsapi_ticket) sign = Sign(jsapi_ticket, url) res = sign.sign() res['appid'] = APPID logger.info('res:%s' % res) return self.finish(res)
def get(self): # 根据code获取网页access_token和openid code = self.get_argument('code', None) logger.info('code: %s' % code) try: user_auth = UserAuth(APPID, APPSECRET, code) info_data = user_auth.get_user_info() except Exception as e: return self.write(str(e)) # info_data = { # 'openid': 'oBGCb1GE38DXO03ebeY0MtnfJKmc', # 'nickname': '李家富', # 'sex': 1, # 'language': 'zh_CN', # 'city': '广州', # 'province': '广东', 'country': '中国', # 'headimgurl': 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0EBmjmic8Is2ezTGhysF7JcUjSjnNVOYrCVoOJ6hIBNziaQiaFN76OSIpa7OpdibS3Z2qeGfOSV3mibklxGHV3VLCg/132', # 'privilege': [] # } conn = Postgres() data = conn.fetchone("select id from wx_user where openid = '%s'" % info_data.get('openid')) logger.info('查看数据库是否存在该用户信息: %s' % data) if not data: sql = """ insert into wx_user (openid, username, sex, image_url, province, city, score) values ('%s', '%s', %d, '%s', '%s', '%s', 15); """ % ( info_data.get('openid'), info_data.get('nickname'), info_data.get('sex'), info_data.get('headimgurl'), info_data.get('province'), info_data.get('city') ) end_time = datetime.strftime(datetime.now() + timedelta(days=7), '%Y-%m-%d') sql += """ insert into wx_user_discount_rel (openid, discount_id, end_time) values ('%s', %d, '%s'); """ % (info_data.get('openid'), 1, end_time) conn.execute(sql) else: sql = """ update wx_user set username = '******', sex = %d, image_url = '%s', province = '%s', city = '%s' where openid = '%s' """ % ( info_data.get('nickname'), info_data.get('sex'), info_data.get('headimgurl'), info_data.get('province'), info_data.get('city'), info_data.get('openid') ) conn.execute(sql) user_sql = """ select openid, username, image_url, province, city, score, experience, is_admin, date from wx_user where openid = '%s' """ % info_data.get('openid') user_data = conn.fetchone(user_sql) now = datetime.strftime(datetime.now(), '%Y-%m-%d') discount_sql = """ select wd.id,discount,name,end_time,type,rule from wx_user_discount_rel as wud left join wx_discount as wd on wd.id = wud.discount_id inner join wx_discount_type as wdt on wdt.id = wd.type_id where openid = '%s' and end_time >= '%s' and wud.state = false order by id desc """ % (info_data.get('openid'), now) discount_data = conn.fetchall(discount_sql) info = { 'openid': user_data['openid'], 'username': user_data['username'] or '密语君', 'province': user_data['province'] or '保密', 'city': user_data['city'] or '保密', 'image_url': user_data['image_url'], 'score': user_data['score'], 'experience': user_data['experience'], 'is_admin': user_data['is_admin'], 'discount': len(discount_data), 'discount_list': discount_data, 'is_receive': user_data['date'] >= datetime.strftime(datetime.now(), '%Y-%m-%d') } logger.info('用户信息: %s' % info) return self.render('personal.html', info=info)