def update_banner(self): current_app.logger.info("Admin {} update index banner".format( request.user.username)) form = IndexUpdateBannerForm().valid_data() ibid = form.ibid.data isdelete = form.isdelete.data IndexBanner.query.filter_by_(IBid=ibid).first_('未找到该轮播图信息') with db.auto_commit(): banner_dict = { 'IBid': ibid, 'contentlink': form.contentlink.data, 'IBpic': form.ibpic.data, 'IBsort': form.ibsort.data, 'IBshow': form.ibshow.data, 'isdelete': isdelete } banner_dict = { k: v for k, v in banner_dict.items() if v is not None } banner = IndexBanner.query.filter_by_( IBid=ibid).update(banner_dict) if not banner: raise SystemError('服务器繁忙 10000') return Success('修改成功', {'ibid': ibid})
def _generate_activaty_code(self, num=10): """生成激活码""" code_list = [] rule = ActivationCodeRule.query.filter_by_(ACRisShow=True).first() if rule: num = rule.ACRnum or 10 lowercase = string.ascii_lowercase count = 0 while len(code_list) < num: if count > 10: raise SystemError('激活码库存不足') code = ''.join(random.choice(lowercase) for _ in range(2)) + ''.join( str(random.randint(0, 9)) for _ in range(5)) # 是否与已有重复 is_exists = UserActivationCode.query.filter_by_({ 'UACcode': code, 'UACstatus': UserActivationCodeStatus.wait_use.value }).first() if not is_exists: code_list.append(code) else: count += 1 return code_list
def get_location(self): res = requests.get(self.api_url, params={ 'location': '{},{}'.format(self.lat, self.lng), 'output': 'json', 'ak': BAIDUMPAK }) content = res.json() print(content) if content.get('status') != 0: raise SystemError('数据获取失败') return content.get('result')
def get_answer(self): """通过问题id 获取答案""" if is_supplizer(): user = Supplizer.query.filter(Supplizer.SUid == request.user.id).first() else: user = User.query.filter_(User.USid == request.user.id).first_('用户不存在') data = parameter_required(('quid',)) answer_model = Answer.query.filter_(Answer.QUid == data.get('quid'), Answer.isdelete == False).first() answer_model.fields = self.AnswerFields[:] qu_model = Quest.query.filter_(Quest.QUid == data.get('quid'), Quest.isdelete == False).first() if not qu_model: gennerc_log('可以获取到答案, 但是获取不到问题,id为{0}'.format(data.get('quid'))) raise SystemError('数据异常') answer_model.fill('ququest', qu_model.QUquest) an_instance = AnswerUser.create({ 'QAUid': str(uuid.uuid1()), 'QAid': answer_model.QAid, 'USid': user.USid }) db.session.add(an_instance) return Success('获取回答成功', data=answer_model)
def del_comment(self): """删除评论""" usid = request.user.id user = self.snews.get_user_by_id(usid) current_app.logger.info('User {0} deleted a news commentary'.format( user.USname)) data = parameter_required(('ncid', )) ncid = data.get('ncid') comment = NewsComment.query.filter( NewsComment.NCid == ncid, NewsComment.isdelete == False).first_('未找到该评论或已被删除') if usid == comment.USid: if comment.NCrootid is None: self.snews.del_comment( NewsComment.NCrootid == ncid) # 删除评论下的回复 del_comment = self.snews.del_comment(NewsComment.NCid == ncid) if not del_comment: raise SystemError('服务器繁忙') else: raise AuthorityError('只能删除自己发布的评论') return Success('删除成功', {'ncid': ncid})
def comment_favorite(self): """评论点赞""" usid = request.user.id user = self.snews.get_user_by_id(usid) current_app.logger.info('User {0}, comment favorite'.format( user.USname)) data = parameter_required(('ncid', )) ncid = data.get('ncid') comment = NewsComment.query.filter( NewsComment.NCid == ncid, NewsComment.isdelete == False, NewsComment.NCrootid.is_(None)).first() if not comment: raise NotFound('不支持对回复点赞或评论已删除') is_favorite = self.snews.comment_is_favorite(ncid, usid) with self.snews.auto_commit() as s: if not is_favorite: comment_favorite = NewsCommentFavorite.create({ 'NCFid': str(uuid.uuid1()), 'NCid': ncid, 'USid': usid }) s.add(comment_favorite) msg = '已点赞' else: cancel_favorite = s.query(NewsCommentFavorite).filter( NewsCommentFavorite.NCid == ncid, NewsCommentFavorite.USid == usid).delete_() if not cancel_favorite: raise SystemError('服务器繁忙') msg = '已取消' favorite = self.snews.comment_is_favorite(ncid, usid) fav = 1 if favorite else 0 return Success(msg, {'is_favorite': fav})
def _upload_file(self, file, folder): filename = file.filename shuffix = os.path.splitext(filename)[-1] current_app.logger.info( ">>> Upload File Shuffix is {0} <<<".format(shuffix)) shuffix = shuffix.lower() if self.allowed_file(shuffix): img_name = self.new_name(shuffix) time_now = datetime.now() year = str(time_now.year) month = str(time_now.month) day = str(time_now.day) newPath = os.path.join(current_app.config['BASEDIR'], 'img', folder, year, month, day) if not os.path.isdir(newPath): os.makedirs(newPath) newFile = os.path.join(newPath, img_name) file.save(newFile) # 保存图片 data = '/img/{folder}/{year}/{month}/{day}/{img_name}'.format( folder=folder, year=year, month=month, day=day, img_name=img_name) if shuffix in [ '.mp4', '.avi', '.wmv', '.mov', '.3gp', '.flv', '.mpg' ]: upload_type = 'video' # 生成视频缩略图 thum_origin_name = img_name.split('.')[0] thum_name = video2frames(newFile, newPath, output_prefix=thum_origin_name, extract_time_points=(2, ), jpg_quality=80) video_thum = '/img/{}/{}/{}/{}/{}'.format( folder, year, month, day, thum_name.get('thumbnail_name_list')[0]) dur_second = int(thum_name.get('video_duration', 0)) minute = dur_second // 60 second = dur_second % 60 minute_str = '0' + str(minute) if minute < 10 else str(minute) second_str = '0' + str(second) if second < 10 else str(second) video_dur = minute_str + ':' + second_str if API_HOST == 'https://www.bigxingxing.com': try: self.qiniu.save(data=newFile, filename=data[1:]) except Exception as e: current_app.logger.error( ">>> 视频上传到七牛云出错 : {} <<<".format(e)) raise ParamsError('上传视频失败,请稍后再试') video_thumbnail_path = os.path.join( newPath, thum_name.get('thumbnail_name_list')[0]) if API_HOST == 'https://www.bigxingxing.com': try: self.qiniu.save(data=video_thumbnail_path, filename=video_thum[1:]) except Exception as e: current_app.logger.error( ">>> 视频预览图上传到七牛云出错 : {} <<<".format(e)) else: upload_type = 'image' video_thum = '' video_dur = '' # 读取 # img = Image.open(thumbnail_img) # img_size = '_' + 'x'.join(map(str, img.size)) # path_with_size = thumbnail_img + img_size + shuffix # data += (img_size + shuffix) # img.save(path_with_size) # os.remove(newFile) # 生成压缩图 try: thumbnail_img = CompressPicture().resize_img( ori_img=newFile, ratio=0.8, save_q=80) except Exception as e: current_app.logger.info( ">>> Resize Picture Error : {} <<<".format(e)) raise ParamsError('图片格式错误,请检查后重新上传(请勿强制更改图片后缀名)') data += '_' + thumbnail_img.split('_')[-1] # 上传到七牛云,并删除本地压缩图 if API_HOST == 'https://www.bigxingxing.com': try: self.qiniu.save(data=thumbnail_img, filename=data[1:]) os.remove( str(newFile + '_' + thumbnail_img.split('_')[-1])) except Exception as e: current_app.logger.error( ">>> 图片上传到七牛云出错 : {} <<<".format(e)) raise ParamsError('上传图片失败,请稍后再试') current_app.logger.info( ">>> Upload File Path is {} <<<".format(data)) return data, video_thum, video_dur, upload_type else: raise SystemError(u'上传有误, 不支持的文件类型 {}'.format(shuffix))
def news_favorite(self): """资讯点赞/踩""" usid = request.user.id if usid: user = self.snews.get_user_by_id(usid) current_app.logger.info('User {0} is favorite/trample news'.format( user.USname)) data = parameter_required(('neid', 'tftype')) neid = data.get('neid') news = self.snews.get_news_content({'NEid': neid}) if news.NEstatus != NewsStatus.usual.value: raise StatusError('该资讯当前状态不允许点赞') tftype = data.get('tftype') # {1:点赞, 0:点踩} if not re.match(r'^[01]$', str(tftype)): raise ParamsError('tftype, 参数异常') msg = '已取消' is_favorite = self.snews.news_is_favorite(neid, usid) is_trample = self.snews.news_is_trample(news.NEid, usid) if str(tftype) == '1': if not is_favorite: if is_trample: # raise StatusError('请取消踩后再赞') self.snews.cancel_trample(neid, usid) # 改为自动取消 with self.snews.auto_commit() as s: news_favorite = NewsFavorite.create({ 'NEFid': str(uuid.uuid1()), 'NEid': neid, 'USid': usid }) s.add(news_favorite) msg = '已赞同' else: cancel_favorite = self.snews.cancel_favorite(neid, usid) if not cancel_favorite: raise SystemError('服务器繁忙') else: if not is_trample: if is_favorite: # raise StatusError('请取消赞后再踩') self.snews.cancel_favorite(neid, usid) with self.snews.auto_commit() as sn: news_trample = NewsTrample.create({ 'NETid': str(uuid.uuid1()), 'NEid': neid, 'USid': usid }) sn.add(news_trample) msg = '已反对' else: cancel_trample = self.snews.cancel_trample(neid, usid) if not cancel_trample: raise SystemError('服务器繁忙') favorite = self.snews.news_is_favorite(neid, usid) favorite = 1 if favorite else 0 favorite_count = self.snews.get_news_favorite_count(neid) trample = self.snews.news_is_trample(neid, usid) trample = 1 if trample else 0 trample_count = self.snews.get_news_trample_count(neid) return Success(message=msg, data={ 'neid': neid, 'is_favorite': favorite, 'is_trample': trample, 'favorite_count': favorite_count, 'trample_count': trample_count })
def _pay_detail(self, omclient, opaytype, opayno, mount_price, body, openid='openid'): opaytype = int(opaytype) omclient = int(omclient) body = re.sub("[\s+\.\!\/_,$%^*(+\"\'\-_]+|[+——!,。?、~@#¥%……&*()]+", '', body) mount_price = 0.01 if API_HOST != 'https://www.bigxingxing.com' else mount_price current_app.logger.info('openid is {}, out_trade_no is {} '.format( openid, opayno)) # 微信支付的单位是'分', 支付宝使用的单位是'元' if opaytype == PayType.wechat_pay.value: try: body = body[:16] + '...' current_app.logger.info('body is {}, wechatpay'.format(body)) wechat_pay_dict = { 'body': body, 'out_trade_no': opayno, 'total_fee': int(mount_price * 100), 'attach': 'attach', 'spbill_create_ip': request.remote_addr } if omclient == Client.wechat.value: # 微信客户端 if not openid: raise StatusError('用户未使用微信登录') # wechat_pay_dict.update(dict(trade_type="JSAPI", openid=openid)) wechat_pay_dict.update({ 'trade_type': 'JSAPI', 'openid': openid }) raw = self.wx_pay.jsapi(**wechat_pay_dict) else: wechat_pay_dict.update({'trade_type': "APP"}) raw = self.wx_pay.unified_order(**wechat_pay_dict) except WeixinPayError as e: raise SystemError('微信支付异常: {}'.format('.'.join(e.args))) elif opaytype == PayType.alipay.value: current_app.logger.info('body is {}, alipay'.format(body)) if omclient == Client.wechat.value: raise SystemError('请选用其他支付方式') else: try: raw = self.alipay.api_alipay_trade_app_pay( out_trade_no=opayno, total_amount=mount_price, subject=body[:66] + '...', ) except Exception: raise SystemError('支付宝参数异常') elif opaytype == PayType.test_pay.value: raw = self.alipay.api_alipay_trade_page_pay( out_trade_no=opayno, total_amount=mount_price, subject=body[10], ) raw = 'https://openapi.alipaydev.com/gateway.do?' + raw else: raise SystemError('请选用其他支付方式') current_app.logger.info('pay response is {}'.format(raw)) return raw