def query_stake_stat(stat_type, stake_type=None, limit=20): """query total stake statistics""" if stat_type is None or not isinstance(stat_type, int): raise InvalidParamsError() if limit is None or not isinstance(limit, int) or limit < 1: limit = 20 if stat_type == 1: # stat by address and/or type if stake_type is None or not isinstance(stake_type, int): stakes = db.session.query(TStake.address, func.sum(TStake.count).label('address_count')). \ group_by(TStake.address).order_by('address_count desc').limit(limit) else: stakes = db.session.query(TStake.address, func.sum(TStake.count).label('address_count')).\ filter(TStake.type == stake_type).group_by(TStake.address).\ order_by('address_count desc').limit(limit) item_name = "address" elif stat_type == 2: # stat by champion team stakes = db.session.query(TStake.item, func.sum(TStake.count).label('team_count')).\ filter(TStake.type == 2).group_by(TStake.item).\ order_by('team_count desc').limit(limit) item_name = "champion" elif stat_type == 3: # stat by scores stakes = db.session.query(TStake.item, func.sum(TStake.count).label('score_count')).\ filter(TStake.type == 3).group_by(TStake.item).\ order_by('score_count desc').limit(limit) item_name = "score" elif stat_type == 4: # stat by favourite team stakes = db.session.query(TStake.item, func.sum(TStake.count).label('team_count')).\ filter(TStake.type == 4).group_by(TStake.item).\ order_by('team_count desc').limit(limit) item_name = "team" data = [] for s in stakes: data.append({item_name: s[0], "count": int(s[1])}) return data
def _disableAlarms(hostid): trigger_get = fowardZ.sendToZabbix(method='trigger.get', params={ 'hostids': hostid, 'output': 'triggerid' }) triggerPrototype_get = fowardZ.sendToZabbix(method='triggerprototype.get', params={ 'hostids': hostid, 'output': 'triggerid' }) triggers = [] triggersPrototype = [] for trigger in trigger_get['result']: triggers.append({'triggerid': trigger['triggerid'], 'status': '1'}) disabled = fowardZ.sendToZabbix(method='trigger.update', params=triggers) disabledPrototype = dict(result=True) if triggerPrototype_get: for triggerPrototype in triggerPrototype_get['result']: triggersPrototype.append({ 'triggerid': triggerPrototype['triggerid'], 'status': '1' }) disabledPrototype = fowardZ.sendToZabbix( method='triggerprototype.update', params=triggersPrototype) if 'result' in disabled and 'result' in disabledPrototype: return 'Disable operation was successful.' else: raise InvalidParamsError( 'It wasnt able to disable alarms on hostid "{0}"'.format(hostid))
def query_stake_history(address): """query stake history of one address""" db.session.commit() if address is None or not isinstance(address, str): raise InvalidParamsError() stakes = TStake.query.filter(TStake.address == address) details = [] #TODO, total bingo stakes need be updated. total_bingo_stakes = 1000 user_deposit = 0.0 user_bingo_stakes = 0 for s in stakes: record = { 'address': s.address, 'item': s.item, 'state': s.state, 'time': time.strftime("%Y-%m-%d %H:%M:%S", s.time.utctimetuple()) } if s.state == 1: user_bingo_stakes += s.count record['money'] = s.count * 100 / total_bingo_stakes else: record['money'] = 0 if s.isAnybit == 0: record['deposit'] = round(float(s.count) / 10, 2) elif s.isAnybit == 1: record['deposit'] = round(float(s.count * 8 / 100), 2) user_deposit += record['deposit'] record['awards'] = s.count record['txid'] = s.txid details.append(record) return { 'deposit': round(user_deposit, 2), 'allawards': round(user_bingo_stakes * 100 / total_bingo_stakes, 2), 'details': details }
def response_obj(self, request, D, version_hint=JSONRPC_VERSION_DEFAULT): version = version_hint response = self.empty_response(version=version) apply_version = { '2.0': self.apply_version_2_0, '1.1': self.apply_version_1_1, '1.0': self.apply_version_1_0 } try: try: # determine if an object is iterable? iter(D) except TypeError as e: raise InvalidRequestError( getattr(e, 'message', e.args[0] if len(e.args) > 0 else None)) # version: validate if 'jsonrpc' in D: if text_type(D['jsonrpc']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version {0} not supported.'.format( D['jsonrpc'])) version = request.jsonrpc_version = response[ 'jsonrpc'] = text_type(D['jsonrpc']) elif 'version' in D: if text_type(D['version']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version {0} not supported.'.format( D['version'])) version = request.jsonrpc_version = response[ 'version'] = text_type(D['version']) else: version = request.jsonrpc_version = JSONRPC_VERSION_DEFAULT # params: An Array or Object, that holds the actual parameter values # for the invocation of the procedure. Can be omitted if empty. if 'params' not in D or not D['params']: D['params'] = [] if 'method' not in D or 'params' not in D: raise InvalidParamsError( 'Request requires str:"method" and list:"params"') if D['method'] not in self.urls: raise MethodNotFoundError('Method not found. Available methods: {0}' \ .format('\n'.join(list(self.urls.keys())))) method = self.urls[text_type(D['method'])] if getattr(method, 'json_validate', False): validate_params(method, D) if 'id' in D and D['id'] is not None: # regular request response['id'] = D['id'] if version in ('1.1', '2.0'): response.pop('error', None) else: # notification return None, 204 R = apply_version[version](method, D['params']) if 'id' not in D or ('id' in D and D['id'] is None): # notification return None, 204 if isinstance(R, Response): if R.status_code == 200: return R, R.status_code if R.status_code == 401: raise InvalidCredentialsError(R.status) raise OtherError(R.status, R.status_code) try: # New in Flask version 0.10. encoder = current_app.json_encoder() except AttributeError: encoder = json.JSONEncoder() # type of `R` should be one of these or... if not sum([isinstance(R, e) for e in \ string_types + integer_types + \ (float, complex, dict, list, tuple, set, frozenset, NoneType, bool)]): try: rs = encoder.default( R) # ...or something this thing supports except TypeError as exc: raise TypeError( 'Return type not supported, for {0!r}'.format(R)) response['result'] = R status = 200 except Error as e: response['error'] = e.json_rpc_format if version in ('1.1', '2.0'): response.pop('result', None) status = e.status except HTTPException as e: other_error = OtherError(e) response['error'] = other_error.json_rpc_format response['error']['code'] = e.code if version in ('1.1', '2.0'): response.pop('result', None) status = e.code except Exception as e: other_error = OtherError(e) response['error'] = other_error.json_rpc_format status = other_error.status if version in ('1.1', '2.0'): response.pop('result', None) # Exactly one of result or error MUST be specified. It's not # allowed to specify both or none. if version in ('1.1', '2.0') and 'result' in response: response.pop('error', None) return response, status
def query_stake_memo(stake_type, stake_item): if stake_type != 2 or stake_item < 1 or stake_item > 32: raise InvalidParamsError() str_memo = str(stake_item) + ":2" return bytes.decode(base64.b64encode(str.encode(str_memo)))
def response_dict(self, request, D, is_batch=False, version_hint='1.0'): version = version_hint response = self.empty_response(version=version) apply_version = { '2.0': lambda f, p: f(**encode_kw(p)) if type(p) is dict else f(*p), '1.1': lambda f, p: f(*encode_arg11(p), **encode_kw(encode_kw11(p))), '1.0': lambda f, p: f(*p) } try: # params: An Array or Object, that holds the actual parameter values # for the invocation of the procedure. Can be omitted if empty. if 'params' not in D or not D['params']: D['params'] = [] if 'method' not in D or 'params' not in D: raise InvalidParamsError( 'Request requires str:"method" and list:"params"') if D['method'] not in self.urls: raise MethodNotFoundError('Method not found. Available methods: {0}' \ .format('\n'.join(list(self.urls.keys())))) if 'jsonrpc' in D: if text_type(D['jsonrpc']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version {0} not supported.'.format( D['jsonrpc'])) version = request.jsonrpc_version = response[ 'jsonrpc'] = text_type(D['jsonrpc']) elif 'version' in D: if text_type(D['version']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version {0} not supported.'.format( D['version'])) version = request.jsonrpc_version = response[ 'version'] = text_type(D['version']) else: request.jsonrpc_version = '1.0' method = self.urls[text_type(D['method'])] if getattr(method, 'json_validate', False): validate_params(method, D) if 'id' in D and D['id'] is not None: # regular request response['id'] = D['id'] if version in ('1.1', '2.0') and 'error' in response: response.pop('error') elif is_batch: # notification, not ok in a batch format, but happened anyway raise InvalidRequestError else: # notification return None, 204 R = apply_version[version](method, D['params']) if asyncio.iscoroutine(R): R = (yield from R) if 'id' not in D or ('id' in D and D['id'] is None): # notification return None, 204 encoder = current_app.json_encoder() # type of `R` should be one of these or... if not sum([isinstance(R, e) for e in \ string_types + integer_types + (dict, list, set, NoneType, bool)]): try: rs = encoder.default( R) # ...or something this thing supports except TypeError as exc: raise TypeError( "Return type not supported, for {0!r}".format(R)) response['result'] = R status = 200 except Error as e: # exception missed by others #got_request_exception.connect(log_exception, current_app._get_current_object()) response['error'] = e.json_rpc_format if version in ('1.1', '2.0') and 'result' in response: response.pop('result') status = e.status except HTTPException as e: # exception missed by others #got_request_exception.connect(log_exception, current_app._get_current_object()) other_error = OtherError(e) response['error'] = other_error.json_rpc_format response['error']['code'] = e.code if version in ('1.1', '2.0') and 'result' in response: response.pop('result') status = e.code except Exception as e: # exception missed by others #got_request_exception.connect(log_exception, current_app._get_current_object()) other_error = OtherError(e) response['error'] = other_error.json_rpc_format status = other_error.status if version in ('1.1', '2.0') and 'result' in response: response.pop('result') # Exactly one of result or error MUST be specified. It's not # allowed to specify both or none. if version in ('1.1', '2.0' ) and 'error' in response and not response['error']: response.pop('error') return response, status
def response_dict(self, request, D, is_batch=False, version_hint='1.0'): version = version_hint response = self.empty_response(version=version) apply_version = { '2.0': lambda f, r, p: f(**encode_kw(p)) if type(p) is dict else f(*p), '1.1': lambda f, r, p: f(*encode_arg11(p), **encode_kw(encode_kw11(p))), '1.0': lambda f, r, p: f(*p) } try: # params: An Array or Object, that holds the actual parameter values # for the invocation of the procedure. Can be omitted if empty. if 'params' not in D or not D['params']: D['params'] = [] if 'method' not in D or 'params' not in D: raise InvalidParamsError( 'Request requires str:"method" and list:"params"') if D['method'] not in self.urls: raise MethodNotFoundError( 'Method not found. Available methods: %s' % ('\n'.join(self.urls.keys()))) if 'jsonrpc' in D: if str(D['jsonrpc']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version %s not supported.' % D['jsonrpc']) version = request.jsonrpc_version = response['jsonrpc'] = str( D['jsonrpc']) elif 'version' in D: if str(D['version']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version %s not supported.' % D['version']) version = request.jsonrpc_version = response['version'] = str( D['version']) else: request.jsonrpc_version = '1.0' method = self.urls[str(D['method'])] if getattr(method, 'json_validate', False): validate_params(method, D) if 'id' in D and D['id'] is not None: # regular request response['id'] = D['id'] if version in ('1.1', '2.0') and 'error' in response: response.pop('error') elif is_batch: # notification, not ok in a batch format, but happened anyway raise InvalidRequestError else: # notification return None, 204 R = apply_version[version](method, request, D['params']) if 'id' not in D or ('id' in D and D['id'] is None): # notification return None, 204 encoder = current_app.json_encoder() if not sum( map( lambda e: isinstance( R, e), # type of `R` should be one of these or... (dict, str, unicode, int, long, list, set, NoneType, bool))): try: rs = encoder.default( R) # ...or something this thing supports except TypeError, exc: raise TypeError("Return type not supported, for %r" % R) response['result'] = R status = 200
def getTrigger(hosts=None, hostgroups=None, withAck=2, maxAge=None, lastChangeSince=None, lastChangeTill=None, output='extend'): extend = [ 'triggerid', 'description', 'expression', 'comments', 'error', 'flags', 'lastchange', 'priority', 'state', 'status', 'templateid', 'type', 'url', 'value' ] triggers = getAllTriggersAlarming() triggers_the_user_will_see = list() hostgroups = addGroup(hostgroups) hostgroups[:] = [n2i.hostgroup(hostgroup) for hostgroup in hostgroups] hosts = addGroup(hosts) '''filtro por hosts''' if hosts: for trigger in triggers['result']: for host in trigger['hosts']: if host['name'] in hosts: triggers_the_user_will_see.append(trigger) else: triggers_the_user_will_see = triggers['result'] '''filtro por hostgroups''' if hostgroups: triggers_the_user_will_see[:] = [ trigger for trigger in triggers_the_user_will_see for group in trigger['groups'] if group['groupid'] in hostgroups ] '''filtro por ack''' withAck = str(withAck) if withAck not in ('0', '1', '2'): raise InvalidParamsError('Value {0} not permitted.'.format(withAck)) else: if withAck == '2': pass elif withAck == '1': triggers_the_user_will_see[:] = [ trigger for trigger in triggers_the_user_will_see if trigger['lastEvent'] and trigger['lastEvent']['acknowledged'] == '1' ] else: triggers_the_user_will_see[:] = [ trigger for trigger in triggers_the_user_will_see if not trigger['lastEvent'] or trigger['lastEvent']['acknowledged'] == '0' ] '''filtro por data ~custom: por dias~''' if maxAge: since_date = datetime.now() - timedelta(maxAge) since_timestamp = time.mktime(since_date.timetuple()) triggers_the_user_will_see[:] = [ trigger for trigger in triggers_the_user_will_see if int(trigger['lastchange']) > since_timestamp ] '''filtro por data a partir de''' if lastChangeSince: triggers_the_user_will_see[:] = [ trigger for trigger in triggers_the_user_will_see if trigger['lastchange'] > lastChangeSince ] '''filtro por data ate''' if lastChangeTill: triggers_the_user_will_see[:] = [ trigger for trigger in triggers_the_user_will_see if trigger['lastchange'] < lastChangeTill ] if output is not 'extend': for attribute in output: extend.remove(attribute) for trigger in triggers_the_user_will_see: for attribute in extend: trigger.pop(attribute) return triggers_the_user_will_see