async def save_statistic_data(cls, feature='', success=0, failure=0, ignored=0): sum = success + failure + ignored if cls.ENV == "Local": url = 'http://localhost:8085/statistic/msn_cms' else: url = 'http://msnapi.eastasia.cloudapp.azure.com/statistic/msn_cms' res = await cls.Request(headers={}, endpoint=url, methods='post', json={ "feature": feature, "sum": sum, "success": success, "failure": failure, "ignored": ignored, "env": cls.ENV }) if 'error' in res: logging.info('save statistic data failed') message = Util.format_Resp(code_type=CodeStatus.RequestError, message='save statistic data failed', exception=res['error'], sys_obj=sys._getframe()) else: logging.info('Save statistic data successfully') message = Util.format_Resp(data='Save statistic data successfully')
async def get_all(cls, page=None, pageSize=None, filterParams={}): filterObj = cls.filter(**filterParams) if page and pageSize: data = list( map( lambda x: cls.toDict(x), await filterObj.offset( (int(page) - 1) * int(pageSize)).limit(int(pageSize)))) return Util.format_Resp(data=data, count=await filterObj.count(), curPage=page) else: data = [cls.toDict(item) for item in await filterObj.all()] return Util.format_Resp(data=data)
async def send_mail_by_msn_api(cls, subject, to, data, cc=None, bcc=None, template_path=None, feature=None): ''' 调用msn_api发送邮件 :param subject: :param to: :param data: :param cc: :param bcc: :param template_path: :return: ''' if cls.ENV == "Local": url = 'http://localhost:8085/mail/msn_cms' else: url = 'http://msnapi.eastasia.cloudapp.azure.com/mail/msn_cms' template_dir = Path(__file__).parent / 'templates' env = Environment(loader=FileSystemLoader(str(template_dir)), trim_blocks=True) body = env.get_template(template_path).render(data=data) headers = {'sender': "MMAIS-MSN"} res = await cls.Request(headers=headers, endpoint=url, methods='post', json={ "subject": subject, "body": body, "to": to, "cc": cc, "bcc": bcc, "feature": feature, "env": cls.ENV }) response = res.get('response') if 'error' in response: logging.info('send mail {} failed'.format(to)) message = Util.format_Resp(code_type=CodeStatus.SendMailError, message='send mail failed', exception=res['error'], sys_obj=sys._getframe()) else: logging.info('Send mail {} successfully'.format(to)) message = Util.format_Resp(data='Send mail successfully') return message
async def error_middleware(request, handler): try: response = await handler(request) return response except web.HTTPException as ex: if ex.status == 404: res = Util.format_Resp(code_type=CodeStatus.NotFound, alert='page not found') return web.json_response(res, status=CodeStatus.NotFound.value) raise except: exp = sys.exc_info() data = Util.format_Resp(code_type=CodeStatus.UnknownError, exp_obj=exp) logging.error(data.get('errorDetail')) return web.json_response(data)
async def get_one(cls, filterParams=None): if filterParams: queryObj = await cls.get_or_none(**filterParams) if not queryObj: data = {} else: data = cls.toDict(queryObj) else: data = cls.toDict(await cls.first()) return Util.format_Resp(data=data)
async def update(cls, data): ''' 更新,如果没有传id则为新增 :param data: :return: ''' id = data.get("id") if not id: return await cls.add(data) del data["id"] if data.get("start_datetime") and data.get("end_datetime"): data["work_hours"] = Util.cal_work_hour(data.get("start_datetime"), data.get("end_datetime")) await cls.filter(id=id).update(**data) return Util.format_Resp(message="更新成功")
async def api_middleware(request, handler): ''' :param request: :param handler: :return: ''' from app import app ip = request.remote if "docs" in request.path: return await handler(request) headers = request.headers token = headers.get("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI1NSIsImN1c3RvbWVySWQiOiIxNTkyMDY1MjE0IiwidXNlcm5hbWUiOiLpooTnoJTmuKnlrqQiLCJhdXRob3JpdGllcyI6IiIsImV4cCI6MTYwODExMDY0MH0.K2wbpHLx9InscxERKD8qvFynVJoiXLDaORmX6GB0reCXL8Nirxi1NZeSvskm74IlT4NpoUPRkvKwP10vRwECwQ") # config = await app.redis.hkeys(token) # if not config: data = (await Lib.Request(headers={"Authorization": "Bearer {}".format(token)}, endpoint="https://agro-iot.auto-control.com.cn/api/user")).get("response", {}).get( "data", {}) if data: del data['createDate'] del data['modifiedDate'] del data['active'] await app.redis.hmset_dict( token, data) else: return web.json_response(Util.format_Resp(code_type=CodeStatus.BadRequest, message="登陆失败")) # else: # data = await app.redis.hgetall(token, encoding="utf-8") ''' data中字段 "id": 6, "customerId": 1586272542, "createDate": "2020-04-08 07:15:42", "modifiedDate": "2020-12-17 01:27:04", "phoneNumber": "13911682107", "username": "******", "nickname": "奥托测试", "avatar": "", "password": "", "roles": "ADMIN", "active": true ''' for k, v in data.items(): setattr(request, k, v) request.token = token return await handler(request)
async def add_all(cls, data): for item in data: await cls(**item).save() return Util.format_Resp(message="添加成功")
async def add(cls, data): await cls(**data).save() return Util.format_Resp(message="添加成功")
async def remove(cls, id): await cls.filter(id=id).delete() return Util.format_Resp(message="删除成功")
async def delete(cls, fileName): async with asyncoss.Bucket(cls.auth, cls.endpoint, cls.bucketName) as bucket: await bucket.delete_object(fileName) return Util.format_Resp(message="delete successfully")