code stringlengths 1 18.2k |
|---|
the session be terminated after this response? :param reprompt_text, reprompt_ssml: Works the same as `text`/`ssml`, but instead sets the reprompting speech output. """ obj = { 'version': '1.0', 'response': { 'outputSpeech': {'type': 'PlainText', 'text': ''}, 'shouldEndSession': end_session }, 'sessionAttributes': attr... |
reprompt_output = {'type': 'PlainText', 'text': reprompt_text} elif reprompt_ssml: reprompt_output = {'type': 'SSML', 'ssml': reprompt_ssml} if reprompt_output: obj['response']['reprompt'] = {'outputSpeech': reprompt_output} return obj |
def reprompt(text=None, ssml=None, attributes=None): """Convenience method to save a little bit of typing for the common case of reprompting the user. Simply calls :py:func:`alexandra.util.respond` with the given arguments and holds the session open. One of either the `text` or `ssml` should be provided if any speech o... |
Dictionary of attributes to store in the current session """ return respond( reprompt_text=text, reprompt_ssml=ssml, attributes=attributes, end_session=False ) |
def validate_request_timestamp(req_body, max_diff=150): """Ensure the request's timestamp doesn't fall outside of the app's specified tolerance. Returns True if this request is valid, False otherwise. :param req_body: JSON object parsed out of the raw POST data of a request. :param max_diff: Maximum allowable differenc... |
if not time_str: log.error('timestamp not present %s', req_body) return False req_ts = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%SZ") diff = (datetime.utcnow() - req_ts).total_seconds() if abs(diff) > max_diff: log.error('timestamp difference too high: %d sec', diff) return False return True |
def validate_request_certificate(headers, data): """Ensure that the certificate and signature specified in the request headers are truely from Amazon and correctly verify. Returns True if certificate verification succeeds, False otherwise. :param headers: Dictionary (or sufficiently dictionary-like) map of request head... |
'Signature' not in headers: log.error('invalid request headers') return False cert_url = headers['SignatureCertChainUrl'] sig = base64.b64decode(headers['Signature']) cert = _get_certificate(cert_url) if not cert: return False try: # ... wtf kind of API decision is this crypto.verify(cert, sig, data, 'sha1') return Tru... |
def _get_certificate(cert_url): """Download and validate a specified Amazon PEM file.""" global _cache if cert_url in _cache: cert = _cache[cert_url] if cert.has_expired(): _cache = {} else: return cert url = urlparse(cert_url) host = url.netloc.lower() path = posixpath.normpath(url.path) # Sanity check location so we ... |
cert location %s', cert_url) return resp = urlopen(cert_url) if resp.getcode() != 200: log.error('failed to download certificate') return cert = crypto.load_certificate(crypto.FILETYPE_PEM, resp.read()) if cert.has_expired() or cert.get_subject().CN != 'echo-api.amazon.com': log.error('certificate expired or invalid') ... |
def is_processed(self, db_versions): """Check if version is already applied in the database. :param db_versions: """ return self.number in (v.number for v in db_versions if v.date_done) |
def is_noop(self): """Check if version is a no operation version. """ has_operations = [mode.pre_operations or mode.post_operations for mode in self._version_modes.values()] has_upgrade_addons = [mode.upgrade_addons or mode.remove_addons for mode in self._version_modes.values()] noop = not any((has_upgrade_addons, has_... |
def _get_version_mode(self, mode=None): """Return a VersionMode for a mode name. When the mode is None, we are working with the 'base' mode. """ version_mode = self._version_modes.get(mode) if not version_mode: version_mode = self._version_modes[mode] = VersionMode(name=mode) return version_mode |
def add_operation(self, operation_type, operation, mode=None): """Add an operation to the version :param mode: Name of the mode in which the operation is executed :type mode: str :param operation_type: one of 'pre', 'post' :type operation_type: str :param operation: the operation to add :type operation: :class:`marabun... |
must be 'pre' or 'post', got %s" % (operation_type,) ) |
def add_backup_operation(self, backup, mode=None): """Add a backup operation to the version. :param backup: To either add or skip the backup :type backup: Boolean :param mode: Name of the mode in which the operation is executed For now, backups are mode-independent :type mode: String """ try: if self.options.backup: se... |
def pre_operations(self, mode=None): """ Return pre-operations only for the mode asked """ version_mode = self._get_version_mode(mode=mode) return version_mode.pre_operations |
def post_operations(self, mode=None): """ Return post-operations only for the mode asked """ version_mode = self._get_version_mode(mode=mode) return version_mode.post_operations |
def upgrade_addons_operation(self, addons_state, mode=None): """ Return merged set of main addons and mode's addons """ installed = set(a.name for a in addons_state if a.state in ('installed', 'to upgrade')) base_mode = self._get_version_mode() addons_list = base_mode.upgrade_addons.copy() if mode: add_mode = self._get... |
def copy(self): """ get copy of object :return: ReactionContainer """ return type(self)(reagents=[x.copy() for x in self.__reagents], meta=self.__meta.copy(), products=[x.copy() for x in self.__products], reactants=[x.copy() for x in self.__reactants]) |
def implicify_hydrogens(self): """ remove explicit hydrogens if possible :return: number of removed hydrogens """ total = 0 for ml in (self.__reagents, self.__reactants, self.__products): for m in ml: if hasattr(m, 'implicify_hydrogens'): total += m.implicify_hydrogens() if total: self.flush_cache() return total |
def reset_query_marks(self): """ set or reset hyb and neighbors marks to atoms. """ for ml in (self.__reagents, self.__reactants, self.__products): for m in ml: if hasattr(m, 'reset_query_marks'): m.reset_query_marks() self.flush_cache() |
def compose(self): """ get CGR of reaction reagents will be presented as unchanged molecules :return: CGRContainer """ rr = self.__reagents + self.__reactants if rr: if not all(isinstance(x, (MoleculeContainer, CGRContainer)) for x in rr): raise TypeError('Queries not composable') r = reduce(or_, rr) else: r = Molecule... |
else: p = MoleculeContainer() return r ^ p |
def calculate2d(self, force=True): """ recalculate 2d coordinates. currently rings can be calculated badly. :param force: ignore existing coordinates of atoms """ for ml in (self.__reagents, self.__reactants, self.__products): for m in ml: m.calculate2d(force) self.fix_positions() |
def fix_positions(self): """ fix coordinates of molecules in reaction """ shift_x = 0 for m in self.__reactants: max_x = self.__fix_positions(m, shift_x, 0) shift_x = max_x + 1 arrow_min = shift_x if self.__reagents: for m in self.__reagents: max_x = self.__fix_positions(m, shift_x, 1.5) shift_x = max_x + 1 else: shift... |
shift_x = max_x + 1 self._arrow = (arrow_min, arrow_max) self.flush_cache() |
def get_role_keys(cls, unit_key): """ :param unit_key: Parent unit key :return: role keys of subunits """ stack = Role.objects.filter(unit_id=unit_key).values_list('key', flatten=True) for unit_key in cls.objects.filter(parent_id=unit_key).values_list('key', flatten=True): stack.extend(cls.get_role_keys(unit_key)) retu... |
def get_permissions(self): """ Permissions of the user. Returns: List of Permission objects. """ user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].role return user_role.get_permissions() |
def get_permissions(self): """ Soyut role ait Permission nesnelerini bulur ve code değerlerini döner. Returns: list: Permission code değerleri """ return [p.permission.code for p in self.Permissions if p.permission.code] |
def add_permission(self, perm): """ Soyut Role Permission nesnesi tanımlamayı sağlar. Args: perm (object): """ self.Permissions(permission=perm) PermissionCache.flush() self.save() |
def add_permission_by_name(self, code, save=False): """ Adds a permission with given name. Args: code (str): Code name of the permission. save (bool): If False, does nothing. """ if not save: return ["%s | %s" % (p.name, p.code) for p in Permission.objects.filter(code__contains=code)] for p in Permission.objects.filter... |
def send_notification(self, title, message, typ=1, url=None, sender=None): """ sends a message to user of this role's private mq exchange """ self.user.send_notification(title=title, message=message, typ=typ, url=url, sender=sender) |
def would_move_be_promotion(self): """ Finds if move from current location would be a promotion """ return (self._end_loc.rank == 0 and not self.color) or \ (self._end_loc.rank == 7 and self.color) |
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. If weak is True, then receiver must be weak referenceable. Receivers must be able to ac... |
another receiver was already connected with that dispatch_uid. sender The sender to which the receiver should respond. Must either be of type Signal, or None to receive events from any sender. weak Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver... |
used. dispatch_uid An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. """ if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) if weak: ref = weakref.ref recei... |
six.PY3: receiver = ref(receiver) weakref.finalize(receiver_object, self._remove_receiver) else: receiver = ref(receiver, self._remove_receiver) with self.lock: self._clear_dead_receivers() for r_key, _ in self.receivers: if r_key == lookup_key: break else: self.receivers.append((lookup_key, receiver)) self.sender_rece... |
def disconnect(self, receiver=None, sender=None, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be remove from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid... |
(dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender... |
def migrate(config): """Perform a migration according to config. :param config: The configuration to be applied :type config: Config """ webapp = WebApp(config.web_host, config.web_port, custom_maintenance_file=config.web_custom_html) webserver = WebServer(webapp) webserver.daemon = True webserver.start() migration_par... |
it # means that the concurrent process has finished the # migration or that it failed to run it. # In both cases after the lock is released, this process will # verify if it has still to do something (if the other process # failed mainly). application_lock.stop = True application_lock.join() # we are not in the replica... |
on for the # migration try: table = MigrationTable(database) runner = Runner(config, migration, database, table) runner.perform() finally: application_lock.stop = True application_lock.join() |
def main(): """Parse the command line and run :func:`migrate`.""" parser = get_args_parser() args = parser.parse_args() config = Config.from_parse_args(args) migrate(config) |
def get_permissions(cls): """ Generates permissions for all CrudView based class methods. Returns: List of Permission objects. """ perms = [] for kls_name, kls in cls.registry.items(): for method_name in cls.__dict__.keys(): if method_name.endswith('_view'): perms.append("%s.%s" % (kls_name, method_name)) return perms |
def _get_object_menu_models(): """ we need to create basic permissions for only CRUD enabled models """ from pyoko.conf import settings enabled_models = [] for entry in settings.OBJECT_MENU.values(): for mdl in entry: if 'wf' not in mdl: enabled_models.append(mdl['name']) return enabled_models |
def add(cls, code_name, name='', description=''): """ create a custom permission """ if code_name not in cls.registry: cls.registry[code_name] = (code_name, name or code_name, description) return code_name |
def get_mapping(self, other): """ get self to other mapping """ m = next(self._matcher(other).isomorphisms_iter(), None) if m: return {v: k for k, v in m.items()} |
def get_substructure_mapping(self, other, limit=1): """ get self to other substructure mapping :param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None; if > 1 return list of dicts """ i = self._matcher(other).subgraph_isomorphisms_iter() if limit == 1: m = next(i, None) if m: re... |
({v: k for k, v in m.items()} for m in i) return [{v: k for k, v in m.items()} for m in islice(i, limit)] |
def from_string(cls, alg_str): """ Creates a location from a two character string consisting of the file then rank written in algebraic notation. Examples: e4, b5, a7 :type: alg_str: str :rtype: Location """ try: return cls(int(alg_str[1]) - 1, ord(alg_str[0]) - 97) except ValueError as e: raise ValueError("Location.fr... |
def shift(self, direction): """ Shifts in direction provided by ``Direction`` enum. :type: direction: Direction :rtype: Location """ try: if direction == Direction.UP: return self.shift_up() elif direction == Direction.DOWN: return self.shift_down() elif direction == Direction.RIGHT: return self.shift_right() elif dire... |
def shift_up(self, times=1): """ Finds Location shifted up by 1 :rtype: Location """ try: return Location(self._rank + times, self._file) except IndexError as e: raise IndexError(e) |
def shift_down(self, times=1): """ Finds Location shifted down by 1 :rtype: Location """ try: return Location(self._rank - times, self._file) except IndexError as e: raise IndexError(e) |
def shift_right(self, times=1): """ Finds Location shifted right by 1 :rtype: Location """ try: return Location(self._rank, self._file + times) except IndexError as e: raise IndexError(e) |
def shift_left(self, times=1): """ Finds Location shifted left by 1 :rtype: Location """ try: return Location(self._rank, self._file - times) except IndexError as e: raise IndexError(e) |
def shift_up_right(self, times=1): """ Finds Location shifted up right by 1 :rtype: Location """ try: return Location(self._rank + times, self._file + times) except IndexError as e: raise IndexError(e) |
def shift_up_left(self, times=1): """ Finds Location shifted up left by 1 :rtype: Location """ try: return Location(self._rank + times, self._file - times) except IndexError as e: raise IndexError(e) |
def shift_down_right(self, times=1): """ Finds Location shifted down right by 1 :rtype: Location """ try: return Location(self._rank - times, self._file + times) except IndexError as e: raise IndexError(e) |
def shift_down_left(self, times=1): """ Finds Location shifted down left by 1 :rtype: Location """ try: return Location(self._rank - times, self._file - times) except IndexError as e: raise IndexError(e) |
def standardize(self): """ standardize functional groups :return: number of found groups """ self.reset_query_marks() seen = set() total = 0 for n, atom in self.atoms(): if n in seen: continue for k, center in central.items(): if center != atom: continue shell = tuple((bond, self._node[m]) for m, bond in self._adj[n].i... |
attr_value in atom_patch.items(): setattr(atom, attr_name, attr_value) for (bond_patch, atom_patch), (bond, atom) in zip(shell_patch, shell): bond.update(bond_patch) for attr_name, attr_value in atom_patch.items(): setattr(atom, attr_name, attr_value) seen.add(n) seen.update(self._adj[n]) break else: continue break if ... |
def get_staged_files(): """Get all files staged for the current commit. """ proc = subprocess.Popen(('git', 'status', '--porcelain'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, _ = proc.communicate() staged_files = modified_re.findall(out) return staged_files |
def runserver(host=None, port=None): """ Run Tornado server """ host = host or os.getenv('HTTP_HOST', '0.0.0.0') port = port or os.getenv('HTTP_PORT', '9001') zioloop = ioloop.IOLoop.instance() # setup pika client: pc = QueueManager(zioloop) app.pc = pc pc.connect() app.listen(port, host) zioloop.start() |
def open(self): """ Called on new websocket connection. """ sess_id = self._get_sess_id() if sess_id: self.application.pc.websockets[self._get_sess_id()] = self self.write_message(json.dumps({"cmd": "status", "status": "open"})) else: self.write_message(json.dumps({"cmd": "error", "error": "Please login", "code": 401})... |
def on_message(self, message): """ called on new websocket message, """ log.debug("WS MSG for %s: %s" % (self._get_sess_id(), message)) self.application.pc.redirect_incoming_message(self._get_sess_id(), message, self.request) |
def _handle_headers(self): """ Do response processing """ origin = self.request.headers.get('Origin') if not settings.DEBUG: if origin in settings.ALLOWED_ORIGINS or not origin: self.set_header('Access-Control-Allow-Origin', origin) else: log.debug("CORS ERROR: %s not allowed, allowed hosts: %s" % (origin, settings.ALL... |
def post(self, view_name): """ login handler """ sess_id = None input_data = {} # try: self._handle_headers() # handle input input_data = json_decode(self.request.body) if self.request.body else {} input_data['path'] = view_name # set or get session cookie if not self.get_cookie(COOKIE_NAME) or 'username' in input_data... |
'_zops_remote_ip': self.request.remote_ip} log.info("New Request for %s: %s" % (sess_id, input_data)) self.application.pc.register_websocket(sess_id, self) self.application.pc.redirect_incoming_message(sess_id, json_encode(input_data), self.request) |
def load_formatter_fn(formatter): ''' >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...> ''' obj = util.load_object(formatter) if not hasattr(obj, 'ispartial'): obj.ispartial = util.ispartial return obj |
def _remove_redundancy(self, log): """Removes duplicate data from 'data' inside log dict and brings it out. >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> log = {'id' : 46846876, 'type' : 'log', ... 'data' : {'a' : 1, 'b' : 2, 'type' : 'metric'}} >>> lc._remove_redund... |
log['data']: log[key] = log['data'].pop(key) return log |
def validate_log_format(self, log): ''' >>> lc = LogCollector('file=/path/to/file.log:formatter=logagg.formatters.basescript', 30) >>> incomplete_log = {'data' : {'x' : 1, 'y' : 2}, ... 'raw' : 'Not all keys present'} >>> lc.validate_log_format(incomplete_log) 'failed' >>> redundant_log = {'one_invalid_key' : 'Extra in... |
'id': '0112358', ... 'level': 'debug', ... 'raw': 'some log line here', ... 'timestamp': '2018-04-07T14:06:17.404818', ... 'type': 'log'} >>> lc.validate_log_format(redundant_log) 'failed' >>> correct_log = {'data': {'x' : 1, 'y' : 2}, ... 'error': False, ... 'error_tb': '', ... 'event': 'event', ... 'file': '/path/to/... |
'type': 'log'} >>> lc.validate_log_format(correct_log) 'passed' ''' keys_in_log = set(log) keys_in_log_structure = set(self.LOG_STRUCTURE) try: assert (keys_in_log == keys_in_log_structure) except AssertionError as e: self.log.warning('formatted_log_structure_rejected' , key_not_found = list(keys_in_log_structure-keys_... |
def assign_default_log_values(self, fpath, line, formatter): ''' >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> from pprint import pprint >>> formatter = 'logagg.formatters.mongodb' >>> fpath = '/var/log/mongodb/mongodb.log' >>> line = 'some log line here' >>> default... |
'timestamp': '...', 'type': 'log'} ''' return dict( id=None, file=fpath, host=self.HOST, formatter=formatter, event='event', data={}, raw=line, timestamp=datetime.datetime.utcnow().isoformat(), type='log', level='debug', error= False, error_tb='', ) |
def _scan_fpatterns(self, state): ''' For a list of given fpatterns, this starts a thread collecting log lines from file >>> os.path.isfile = lambda path: path == '/path/to/log_file.log' >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> print(lc.fpaths) file=/path/to/log... |
>>> print('formatters loaded:', lc.formatters) >>> print('log file reader threads started:', lc.log_reader_threads) >>> print('files bieng tracked:', state.files_tracked) ''' for f in self.fpaths: fpattern, formatter =(a.split('=')[1] for a in f.split(':', 1)) self.log.debug('scan_fpatterns', fpattern=fpattern, formatt... |
fpaths: try: formatter_fn = self.formatters.get(formatter, load_formatter_fn(formatter)) self.log.info('found_formatter_fn', fn=formatter) self.formatters[formatter] = formatter_fn except (SystemExit, KeyboardInterrupt): raise except (ImportError, AttributeError): self.log.exception('formatter_fn_not_found', fn=formatt... |
self.log_reader_threads[log_key] = log_reader_thread state.files_tracked.append(fpath) time.sleep(self.SCAN_FPATTERNS_INTERVAL) |
def get_links(self, **kw): """ Prepare links of form by mimicing pyoko's get_links method's result Args: **kw: Returns: list of link dicts """ links = [a for a in dir(self) if isinstance(getattr(self, a), Model) and not a.startswith('_model')] return [ { 'field': l, 'mdl': getattr(self, l).__class__, } for l in links ] |
def set_data(self, data): """ Fills form with data Args: data (dict): Data to assign form fields. Returns: Self. Form object. """ for name in self._fields: setattr(self, name, data.get(name)) return self |
def serialize(self): """ Converts the form/model into JSON ready dicts/lists compatible with `Ulakbus-UI API`_. Example: .. code-block:: json { "forms": { "constraints": {}, "model": { "code": null, "name": null, "save_edit": null, }, "grouping": {}, "form": [ { "helpvalue": null, "type": "help" }, "name", "code", "sav... |
Name" }, "name": { "type": "string", "title": "Name" }, "save_edit": { "cmd": "save::add_edit_form", "type": "button", "title": "Save" } }, "title": "Add Permission" } } } """ result = { "schema": { "title": self.title, "type": "object", "properties": {}, "required": [] }, "form": [ { "type": "help", "helpvalue": self.... |
self._model.is_in_db(): result["model"]['object_key'] = self._model.key result["model"]['model_type'] = self._model.__class__.__name__ result["model"]['unicode'] = six.text_type(self._model) # if form intentionally marked as fillable from task data by assigning False to always_blank # field in Meta class, form_data is ... |
'kwargs' in itm and 'value' in itm['kwargs']: itm['value'] = itm['kwargs'].pop('value') if 'kwargs' in itm and 'widget' in itm['kwargs']: item_props['widget'] = itm['kwargs'].pop('widget') if form_data: if form_data[itm['name']] and (itm['type'] == 'date' or itm['type'] == 'datetime'): value_to_serialize = datetime.str... |
needed to fill the form from model # or leave empty else: # if itm['value'] is not None returns itm['value'] # else itm['default'] if itm['value'] is not None: value = itm['value'] else: value = itm['default'] result["model"][itm['name']] = value if itm['type'] == 'model': item_props['model_name'] = itm['model_name'] i... |
by just setting it in "model" dict and bypassing other parts continue else: item_props.update(itm['kwargs']) if itm.get('choices'): self._handle_choices(itm, item_props, result) else: result["form"].append(itm['name']) if 'help_text' in itm: item_props['help_text'] = itm['help_text'] if 'schema' in itm: item_props['sch... |
but do not use it. why is it for? if self.context: if self.context.has_permission("%s.select_list" % item_props['model_name']): item_props.update({ 'list_cmd': 'select_list', 'wf': 'crud', }) if self.context.has_permission("%s.add_edit_form" % item_props['model_name']): item_props.update({ 'add_cmd': 'add_edit_form', '... |
def _cache_form_details(self, form): """ Caches some form details to lates process and validate incoming (response) form data Args: form: form dict """ cache = FormCache() form['model']['form_key'] = cache.form_id form['model']['form_name'] = self.__class__.__name__ cache.set( { 'model': list(form['model'].keys()), # I... |
def _parse_msg_for_mongodb(self, msgs): ''' >>> mdbf = MongoDBForwarder('no_host', '27017', 'deadpool', ... 'chimichanga', 'logs', 'collection') >>> log = [{u'data': {u'_': {u'file': u'log.py', ... u'fn': u'start', ... u'ln': 8, ... u'name': u'__main__'}, ... u'a': 1, ... u'b': 2, ... u'msg': u'this is a dummy log'}, .... |
... u'level': u'info', ... u'raw': u'{...}', ... u'timestamp': u'2018-04-09T09:59:24.733945Z', ... u'type': u'metric'}] >>> records = mdbf._parse_msg_for_mongodb(log) >>> from pprint import pprint >>> pprint(records) [{'_id': u'20180409T095924_aec36d313bdc11e89da654e1ad04f45e', u'data': {u'_': {u'file': u'log.py', u'fn... |
u'metric'}] ''' msgs_list = [] for msg in msgs: try: msg['_id'] = msg.pop('id') except KeyError: self.log.exception('collector_failure_id_not_found', log=msg) msgs_list.append(msg) return msgs_list |
def _tag_and_field_maker(self, event): ''' >>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool', ... 'chimichanga', 'logs', 'collection') >>> log = {u'data': {u'_': {u'file': u'log.py', ... u'fn': u'start', ... u'ln': 8, ... u'name': u'__main__'}, ... u'a': 1, ... u'b': 2, ... u'__ignore_this': 'some_string', ...... |
... u'id': u'20180409T095924_aec36d313bdc11e89da654e1ad04f45e', ... u'level': u'info', ... u'raw': u'{...}', ... u'timestamp': u'2018-04-09T09:59:24.733945Z', ... u'type': u'metric'} >>> tags, fields = idbf._tag_and_field_maker(log) >>> from pprint import pprint >>> pprint(tags) {u'data.msg': u'this is a dummy log', u'... |
flatten_dict({'data': data}) t = dict((k, event[k]) for k in event if k not in self.EXCLUDE_TAGS) f = dict() for k in data: v = data[k] if is_number(v) or isinstance(v, MarkValue): f[k] = v else: #if v.startswith('_'): f[k] = eval(v.split('_', 1)[1]) t[k] = v return t, f |
def _parse_msg_for_influxdb(self, msgs): ''' >>> from logagg.forwarders import InfluxDBForwarder >>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool', ... 'chimichanga', 'logs', 'collection') >>> valid_log = [{u'data': {u'_force_this_as_field': 'CXNS CNS nbkbsd', ... u'a': 1, ... u'b': 2, ... u'msg': u'this is a ... |
... u'raw': u'{...}', ... u'timestamp': u'2018-04-09T09:59:24.733945Z', ... u'type': u'metric'}] >>> pointvalues = idbf._parse_msg_for_influxdb(valid_log) >>> from pprint import pprint >>> pprint(pointvalues) [{'fields': {u'data._force_this_as_field': "'CXNS CNS nbkbsd'", u'data.a': 1, u'data.b': 2}, 'measurement': u's... |
[] >>> invalid_log = valid_log >>> invalid_log[0]['type'] = 'log' >>> pointvalues = idbf._parse_msg_for_influxdb(invalid_log) >>> pprint(pointvalues) [] ''' series = [] for msg in msgs: if msg.get('error'): continue if msg.get('type').lower() == 'metric': time = msg.get('timestamp') measurement = msg.get('event') tags,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.