def visitMethodCall(self, ctx: confprolParser.MethodCallContext): name = ctx.ID().getText() if ctx.before.has_attribute(name): expression = ctx.before.get_attribute(name) else: raise RuntimeException( ctx.start.line, AttributeNotDefined(ctx.before.name, ctx.before.type, name)) arg_node = ctx.arguments() if arg_node is None: arguments = [] else: arguments = self.visitArguments(arg_node) try: expr = self.handler.run_function(expression, arguments, ctx.start.line) expr = expr.copy() arguments_name = list(map(lambda a: a.name, arguments)) expr.name = f"{expression.name}(" + ",".join(arguments_name) + ")" return expr except ConfprolException as e: raise RuntimeException(ctx.start.line, e)
def get_userid_from_code(code: str) -> str: wechat_config = config['wechat'] access_token = wechat.get_app_token(WechatAPP.BACKEND) url = wechat_config['userinfourl'] params = {'access_token': access_token, 'code': code} resp = requests.get(url=url, params=params) if resp.status_code != 200: raise RuntimeException('发送请求获取用户信息返回!200', extra={ 'token': access_token, 'code': code, 'resp': resp.text }) body = resp.json() if body.get('errcode', 0) != 0: raise RuntimeException('调用API获取用户信息返回错误', extra={ 'token': access_token, 'code': code, 'errcode': body.get('errcode'), 'errmsg': body.get('errmsg') }) return body.get('UserId')
def generate_qrcode(qrcodeid: int): """ 调用 API 生成二维码 """ minprogram_config = config['minprogram'] qrcode_config = minprogram_config['qrcode'] createurl = '{endpoint}?access_token={token}'.format( endpoint=qrcode_config['createurl'], token=wechat.get_minprogram_token()) path = '{home}?source={source}'.format(home=minprogram_config['homepage'], source=qrcodeid) resp = requests.post(createurl, json={'path': path}) if resp.status_code != 200: raise RuntimeException('发送请求生产二维码返回!200', extra={'resp': resp.text}) if 'application/json' in resp.headers.get('Content-Type'): body = resp.json() raise RuntimeException('调用API生产二维码返回错误', extra={ 'errcode': body['errcode'], 'errmsg': body['errmsg'], 'resp': resp.text }) return resp.content
def import_path(self, path, import_id, line, base_path): if not os.path.isabs(path): path = os.path.join( base_path, path ) # Makes the path relative to the confprol program executed. from visitor import MyVisitor try: lexer = confprolLexer(FileStream(path, ENCODING)) stream = CommonTokenStream(lexer) parser = confprolParser(stream) parser.removeErrorListener(ConsoleErrorListener.INSTANCE) parser.addErrorListener(MyErrorListener()) tree = parser.program() new_base_path = os.path.dirname(os.path.realpath(path)) visitor = MyVisitor(ConfprolHandler(), new_base_path) visitor.visit(tree) expr = ObjectExpression(import_id) imported_variables = visitor.get_context().variables expr.set_attributes(imported_variables) self.assign_variable(import_id, expr) except FileNotFoundError: raise RuntimeException(line, FileNotFound(path)) except (PermissionError, IsADirectoryError): raise RuntimeException(line, CannotOpenDirectory(path))
def run_function(self, callable: RunnableExpression, arguments, line): if callable.type != ValueType.FUNCTION: raise RuntimeException(line, NotCallable(callable.name)) try: return callable.run(arguments) except (ArgumentsMissing, TooManyArguments) as e: raise RuntimeException(line, e)
def visit_call_expr(self, expr: ex.Call) -> LoxValue: callee = self._evaluate(expr.callee) arguments = [] for argument in expr.arguments: arguments.append(self._evaluate(argument)) if not isinstance(callee, LoxCallable): raise RuntimeException(expr.paren, 'Can only call functions and classes.') function = callee if len(arguments) != function.arity: raise RuntimeException( expr.paren, f'Expected {function.arity} arguments, but got {len(arguments)}.' ) return callee.call(self, arguments)
def visitWhile_not_loop(self, ctx: confprolParser.While_not_loopContext): try: value = super().visit(ctx.expr()).to_boolean() except ConfprolException as e: raise RuntimeException(ctx.start.line, e) while not value: statements = ctx.statement() for s in statements: super().visit(s) try: value = super().visit(ctx.expr()).to_boolean() except ConfprolException as e: raise RuntimeException(ctx.start.line, e)
def create_qrcode(name: str = None, owner: str = None, remark: str = None): try: with transaction(): record = { 'name': name, 'owner': owner, 'remark': remark, 'imagename': '' } qrcodeid = QrCodeDAO.insert(record) qrcodeservice.generate_qrcode(qrcodeid=qrcodeid, imagename='%d.jpg' % qrcodeid) QrCodeDAO.update({'imagename': '%d.jpg' % qrcodeid}, id=qrcodeid) return str(qrcodeid), 201 except BusinessException as e: logger.exception('创建二维码业务错误') return e.msg, e.errcode except Exception as e: raise RuntimeException('创建二维码异常', extra={'name': name, 'owner': owner, 'remark': remark}) \ from e
def get(self, name: Token) -> LoxValue: if name.lexeme in self.fields: return self.fields[name.lexeme] method = self.klass.find_method(name.lexeme) if method is not None: return method.bind(self) raise RuntimeException(name, f"Undefined property '{name.lexeme}'.")
def get_order_statistic(handler: str = None, source: int = None): try: today = datetime_utils.utc8now().date() periods = [ TodayPeriod(today=today), ThisWeekPeriod(today=today), ThisMonthPeriod(today=today), ThisSeasonPeriod(today=today), HalfyearPeriod(today=today), ThisYearPeriod(today=today) ] statistic = { p.name: OrderDAO.count(handler=handler, source=source, startdate=p.startdate.strftime('%Y-%m-%d'), enddate=p.enddate.strftime('%Y-%m-%d')) for p in periods } for status in [ OrderStatus.WAITING, OrderStatus.WORKING, OrderStatus.DONE ]: statistic[status.name.lower()] = OrderDAO.count( handler=handler, source=source, status=status.value) return ujson.dumps(statistic) except Exception as e: raise RuntimeException('获取订单统计异常', extra={'handler': handler, 'source': source}) \ from e
def assign(self, name: Token, value: LoxValue) -> None: if name.lexeme in self.values: self.values[name.lexeme] = value elif self.enclosing is not None: self.enclosing.assign(name, value) else: raise RuntimeException(name, f"Undefined variable '{name.lexeme}'")
def get_pageview_statistic(source: int = None): try: today = datetime_utils.utc8now().date() periods = [ TodayPeriod(today=today), ThisWeekPeriod(today=today), ThisMonthPeriod(today=today), ThisSeasonPeriod(today=today), HalfyearPeriod(today=today), ThisYearPeriod(today=today) ] statistic = { p.name: PageViewDAO.sum(source=source, startdate=p.startdate.strftime('%Y-%m-%d'), enddate=p.enddate.strftime('%Y-%m-%d')) for p in periods } return ujson.dumps(statistic) except Exception as e: raise RuntimeException('获取页面访问统计异常', extra={'source': source}) \ from e
def visitExprEqual(self, ctx: confprolParser.ExprEqualContext): value1 = self.visit(ctx.expr(0)) value2 = self.visit(ctx.expr(1)) try: return self.handler.equal(value1, value2) except ConfprolException as e: raise RuntimeException(ctx.start.line, e)
def visit_set_expr(self, expr: Set) -> LoxValue: obj = self._evaluate(expr.object) if not isinstance(obj, LoxInstance): raise RuntimeException(expr.name, 'Only instances have fields.') value = self._evaluate(expr.value) obj.set(expr.name, value) return value
def get(self, name: Token) -> LoxValue: if name.lexeme in self.values: return self.values[name.lexeme] elif self.enclosing is not None: return self.enclosing.get(name) else: raise RuntimeException(name, f"Undefined variable '{name.lexeme}'.")
def deleteoperator(operatorid): try: OperatorDAO.update({'disabled': 1}, id=operatorid) return '', 204 except Exception as e: raise RuntimeException('删除供应商异常', extra={'operatorid': operatorid}) \ from e
def deletebiz(bizid): try: BizDAO.update({'disabled': 1}, id=bizid) return '', 204 except Exception as e: raise RuntimeException('删除套餐异常', extra={'bizid': bizid}) \ from e
def updateoperator(operatorid, name: str = None): try: OperatorDAO.update({'name': name}, id=operatorid) return '', 204 except Exception as e: raise RuntimeException('更新供应商名称异常', extra={'operatorid': operatorid, 'name': name}) \ from e
def createbiz(**kwargs): try: with transaction(): bizid = BizDAO.insert({**kwargs}) return str(bizid), 201 except Exception as e: raise RuntimeException('创建套餐异常', extra={**kwargs}) \ from e
def createoperator(name: str = None): try: operatorid = OperatorDAO.insert({'name': name}) return ujson.dumps({'id': operatorid, 'name': name}), \ 201 except Exception as e: raise RuntimeException('创建供应商异常', extra={'name': name}) \ from e
def visitFunctionCall(self, ctx: confprolParser.FunctionCallContext): function = ctx.ID().getText() arg_node = ctx.arguments() if arg_node is None: arguments = [] else: arguments = self.visitArguments(arg_node) if self.handler.has_attribute(function): try: function = self.handler.get_attribute(function, ctx.start.line) return self.handler.run_function(function, arguments, ctx.start.line) except ConfprolException as e: raise RuntimeException(ctx.start.line, e) else: raise RuntimeException(ctx.start.line, FunctionNotDefined(function))
def updatebiz(bizid, **kwargs): try: with transaction(): BizDAO.update({**kwargs}, id=bizid) return '', 204 except Exception as e: raise RuntimeException('修改套餐异常', extra={'bizid': bizid, **kwargs}) \ from e
def searchorders(pagenum: int = 1, pagesize: int = 20, **kwargs): try: return ujson.dumps( OrderView.search(pagenum=pagenum, pagesize=pagesize, **kwargs)) except Exception as e: raise RuntimeException('搜索订单异常', extra={'pagenum': pagenum, 'pagesize': pagesize, **kwargs}) \ from e
def get_minprogram_token(): client = redis.client() cachekey = CacheKey.apptoken(appname='minprogram') cacheval = client.get(cachekey) if cacheval: return cacheval.decode('UTF-8') # 调用API, 按照微信文档,这个接口比较繁忙,可能会超时。所以最多重试3次,如果3次 # 都超时,则抛出一个业务异常,用 204 表示代码正确执行,但是没有返回任何内容 minprogram_config = config['minprogram'] for i in range(0, 3): resp = requests.get(minprogram_config['tokenurl'], params={'grant_type': 'client_credential', 'appid': minprogram_config['appid'], 'secret': minprogram_config['secret']}) if resp.status_code != 200: raise RuntimeException('发送请求获取小程序TOKEN返回!200', extra={'resp': resp.text}) body = resp.json() # 小程序调用成功居然没有 errocode 这个标示, # 要用 get 来获取,如果没有就是默认成功0 errcode = body.get('errcode', 0) if errcode == 0: client.setex(cachekey, body['access_token'], body['expires_in']) return body['access_token'] elif errcode == -1: time.sleep(2) else: raise RuntimeException('调用API获取小程序TOKEN返回错误', extra={'errcode': body['errcode'], 'errmsg': body['errmsg']}) # 没有异常但也没有return,说明小程序超时 raise BusinessException(errcode=204, msg='微信小程序服务繁忙')
def visitAttribute(self, ctx: confprolParser.AttributeContext): name = ctx.ID().getText() if ctx.before.has_attribute(name): expr = ctx.before.get_attribute(name) expr = expr.copy() expr.name = f"{ctx.before.name}.{name}" return expr else: raise RuntimeException( ctx.start.line, AttributeNotDefined(ctx.before.name, ctx.before.type, name))
def visit_super_expr(self, expr: Super) -> Any: distance = self._locals[expr] superclass = self._environment.get_at(distance, 'super') obj = self._environment.get_at(distance - 1, 'this') if not isinstance(superclass, LoxClass): # unreachable raise RuntimeError('Unreachable code.') method = superclass.find_method(expr.method.lexeme) if method is None: raise RuntimeException( expr.method, f"Undefined property '{expr.method.lexeme}'.") return method.bind(obj)
def getoperatorlist(): try: operators = OperatorDAO.all('id', disabled=0) for operator in operators: operator.pop('disabled') return ujson.dumps(operators) except Exception as e: raise RuntimeException('获取供应商列表异常') \ from e
def get_taged_users(tagid: int) -> list: resp = requests.get(config['wechat']['tagurl'], params={ 'access_token': wechat.get_app_token(WechatAPP.BACKEND), 'tagid': tagid }) if resp.status_code != 200: raise RuntimeException('发送请求获取标签用户返回!200', extra={'tagid': tagid}) body = resp.json() if body.get('errcode', 0) != 0: raise RuntimeException('调用API获取标签用户返回错误', extra={ 'errcode': body.get('errcode'), 'errmsg': body.get('errmsg') }) return body['userlist']
def get_app_token(name: str) -> str: try: client = redis.client() cachekey = CacheKey.apptoken(appname=name) cacheval = client.get(cachekey) if cacheval: return cacheval.decode('UTF-8') corpid = config['wechat']['corpid'] secret = config['apps'][name]['secret'] resp = requests.get(config['wechat']['tokenurl'], params={'corpid': corpid, 'corpsecret': secret}) if resp.status_code != 200: raise RuntimeException('发送请求获取应用TOKEN返回!200', extra={'name': name, 'corpid': corpid, 'secret': secret, 'resp': resp.text}) body = resp.json() if body['errcode'] != 0: raise RuntimeException('调用API获取应用TOKEN返回错误', extra={'name': name, 'corpid': corpid, 'secret': secret, 'errcode': body['errcode'], 'errmsg': body['errmsg']}) token = body['access_token'] client.setex(cachekey, token, body['expires_in']) return token except Exception as e: raise RuntimeException('获取应用Token异常', extra={'name': name}) from e
def send_order_notify_message(title, message, tousers, orderid, realname, mobile, address, operatorname, bizname): # 获取发送通知 token token = wechat.get_app_token(WechatAPP.ORDER) # 构造消息 msg = get_order_message(message=message, realname=realname, mobile=mobile, address=address, operatorname=operatorname, bizname=bizname) # 发送通知 resp = requests.post(config['wechat']['notifyurl'], params={'access_token': token}, json={ 'touser': tousers, 'msgtype': 'textcard', 'agentid': config['apps'][WechatAPP.ORDER]['agentid'], 'textcard': { 'title': title, 'description': msg, 'url': get_order_detail_url(orderid), 'btntxt': '查看详情' } }) if resp.status_code != 200: raise RuntimeException('发送请求发送订单通知返回!200', extra={'resp': resp.text}) body = resp.json() if body.get('errcode', 0) != 0: raise RuntimeException('调用API发送通知返回错误', extra={ 'errcode': body.get('errcode'), 'errmsg': body.get('errmsg') })