code stringlengths 1 18.2k |
|---|
def from_normal(self, hosts=default.ELASTICSEARCH_HOSTS, **kwargs): """ Initialize a Elasticsearch client by specified hosts list. :param hosts: list of nodes we should connect to. Node should be a dictionary ({"host": "localhost", "port": 9200}), the entire dictionary will be passed to the :class:`~elasticsearch.Conne... |
def from_sniffing(self, active_nodes, sniff_on_start=True, sniff_on_connection_fail=True, sniffer_timeout=60, **kwargs): """ Initialize a Elasticsearch client for specify to sniff on startup to inspect the cluster and load balance across all nodes. The client can be configured to inspect the cluster state to get a list... |
def from_ssl(self, ca_certs, client_cert, client_key, hosts=default.ELASTICSEARCH_HOSTS, use_ssl=True, verify_certs=True, **kwargs): """ Initialize a Elasticsearch client by SSL. :param ca_certs: optional path to CA bundle. See https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3 :param cli... |
def transfer_data_from_mongo(self, index, doc_type, use_mongo_id=False, indexed_flag_field_name='', mongo_query_params={}, mongo_host=default.MONGO_HOST, mongo_port=default.MONGO_PORT, mongo_db=default.MONGO_DB, mongo_collection=default.MONGO_COLLECTION): """ Transfer data from MongoDB into the Elasticsearch, the hostn... |
mongo_collection: The name of the collection from MongoDB :return: void """ mongo_client = MongoClient(host=mongo_host, port=int(mongo_port)) try: collection = mongo_client[mongo_db][mongo_collection] if indexed_flag_field_name != '': mongo_query_params.update({indexed_flag_field_name: False}) mongo_docs = collection.f... |
def bulk(self, actions, stats_only=False, **kwargs): """ Executes bulk api by elasticsearch.helpers.bulk. :param actions: iterator containing the actions :param stats_only:if `True` only report number of successful/failed operations instead of just number of successful and a list of error responses Any additional keywo... |
def automatic_syn_data_from_mongo(self, index, doc_type, indexed_flag_field_name, thread_name='automatic_syn_data_thread', interval=60, use_mongo_id=False, mongo_query_params={}, mongo_host=default.MONGO_HOST, mongo_port=default.MONGO_PORT, mongo_db=default.MONGO_DB, mongo_collection=default.MONGO_COLLECTION): """ Auto... |
ElasticsearchClient.automatic_thread_name_counter ElasticsearchClient.automatic_thread_name_counter += 1 thread_id = self._generate_thread_id(thread_name) finally: lock.release() ElasticsearchClient.automatic_syn_data_flag[thread_id] = True t = threading.Thread(target=ElasticsearchClient._automatic_syn_data_from_mongo_... |
def get_simple_info_for_index(self, index=None, params={}, **kwargs): """ Return a list of simple info by specified index (default all), each elements is a dictionary such as { 'health' : 'green', 'status' : 'open', 'index' : 'xxxx', 'uuid' : 'xxxx', 'pri' : 1, 'rep' : 1, `docs_count` : 4, 'docs_deleted' : 0, 'store_si... |
= alter[i] i += 1 dict['docs_deleted'] = alter[i] i += 1 dict['store_size'] = alter[i] i += 1 dict['pri_store_size'] = alter[i] list.append(dict) logger.info('Acquire simple information of the index is done succeeded: %s' % len(list)) return list |
def cluster_health_for_indices(self, index=None, params={}, **kwargs): """ Return a list of cluster health of specified indices(default all), the first element is a dictionary represent a global information of the cluster such as "cluster_name", "number_of_nodes"... the second element represent a indices information li... |
def cluster_health_for_shards(self, index=None, params={}, **kwargs): """ Return a list of cluster health of specified indices(default all) and append shards information of each index the first element is a dictionary represent a global information of the cluster the second element represent a information of indices an... |
def nodes_simple_info(self, params={}, **kwargs): """ Return a dictionary of the nodes simple info that key is a column name, such as [{"http_address": "192.111.111.111", "name" : "test", ...}, ...] """ h = ['name', 'pid', 'http_address', 'version', 'jdk', 'disk.total', 'disk.used_percent', 'heap.current', 'heap.percen... |
def __read_single_fasta_query_lines(f): ''' Read and return sequence of lines (including newlines) that represent a single FASTA query record. The provided file is expected to be blocking. Returns None if there are no more query sequences in the file. ''' def readline(): l = f.readline() if l == '': raise EOFError() re... |
def __read_single_query_result(rs, field_names): ''' Read the result of a single query from the given string, returning a tuple of (record, remaining-string). If no complete record could be read, the first element of the tuple is None and the second element is the original imput string. ''' rf = StringIO.StringIO(rs) d... |
len(fns) l = readline() assert l.endswith(' hits found') nhits = int(l[len('# '):-1 * len(' hits found')]) while nhits > 0: l = readline() field_vals = l.split('\t') assert len(field_vals) == len(field_names) fields = dict(zip(field_names, field_vals)) result.hits.append(Hit(fields)) nhits -= 1 return result, rf.read()... |
def __run_blast_select_loop(input_file, popens, fields): ''' Run the select(2) loop to handle blast I/O to the given set of Popen objects. Yields records back that have been read from blast processes. ''' def make_nonblocking(f): fl = fcntl.fcntl(f.fileno(), fcntl.F_GETFL) fl |= os.O_NONBLOCK fcntl.fcntl(f.fileno(), fc... |
emitting records. Stop # attempting to read from or write to it. If we have # excess data in our result_buffer, c'est la vie. if rbuf == '': p = fd_map[fd]['popen'] rfds.remove(p.stdout.fileno()) p.stdout.close() if not p.stdin.closed: wfds.remove(p.stdin.fileno()) p.stdin.close() continue rs += rbuf while True: rec, r... |
select(2) indicating that # this file descriptor is writable, writes can fail # with EWOULDBLOCK. Handle this gracefully. try: written = os.write(fd, qs) qs = qs[written:] except OSError, e: assert e.errno == errno.EWOULDBLOCK fd_map[fd]['query_buffer'] = qs |
def __run_blast(blast_command, input_file, *args, **kwargs): ''' Run a blast variant on the given input file. ''' # XXX: Eventually, translate results on the fly as requested? Or # just always use our parsed object? if 'outfmt' in kwargs: raise Exception('Use of the -outfmt option is not supported') num_processes = kwa... |
def get_frames(self, channels=2): """Get numpy array of frames corresponding to the segment. :param integer channels: Number of channels in output array :returns: Array of frames in the segment :rtype: numpy array """ tmp_frame = self.track.current_frame self.track.current_frame = self.start frames = self.track.read_fr... |
def duration(self): """Get duration of composition """ return max([x.comp_location + x.duration for x in self.segments]) |
def add_segment(self, segment): """Add a segment to the composition :param segment: Segment to add to composition :type segment: :py:class:`radiotool.composer.Segment` """ self.tracks.add(segment.track) self.segments.append(segment) |
def add_segments(self, segments): """Add a list of segments to the composition :param segments: Segments to add to composition :type segments: list of :py:class:`radiotool.composer.Segment` """ self.tracks.update([seg.track for seg in segments]) self.segments.extend(segments) |
def fade_in(self, segment, duration, fade_type="linear"): """Adds a fade in to a segment in the composition :param segment: Segment to fade in to :type segment: :py:class:`radiotool.composer.Segment` :param duration: Duration of fade-in (in seconds) :type duration: float :returns: The fade that has been added to the co... |
def fade_out(self, segment, duration, fade_type="linear"): """Adds a fade out to a segment in the composition :param segment: Segment to fade out :type segment: :py:class:`radiotool.composer.Segment` :param duration: Duration of fade-out (in seconds) :type duration: float :returns: The fade that has been added to the c... |
def extended_fade_in(self, segment, duration): """Add a fade-in to a segment that extends the beginning of the segment. :param segment: Segment to fade in :type segment: :py:class:`radiotool.composer.Segment` :param duration: Duration of fade-in (in seconds) :returns: The fade that has been added to the composition :rt... |
def extended_fade_out(self, segment, duration): """Add a fade-out to a segment that extends the beginning of the segment. :param segment: Segment to fade out :type segment: :py:class:`radiotool.composer.Segment` :param duration: Duration of fade-out (in seconds) :returns: The fade that has been added to the composition... |
def cross_fade(self, seg1, seg2, duration): """Add a linear crossfade to the composition between two segments. :param seg1: First segment (fading out) :type seg1: :py:class:`radiotool.composer.Segment` :param seg2: Second segment (fading in) :type seg2: :py:class:`radiotool.composer.Segment` :param duration: Duration o... |
seg2.start -= (dur / 2) seg2.duration += (dur / 2) seg2.comp_location -= (dur / 2) seg1.duration += (dur / 2) out_frames = seg1.get_frames(channels=self.channels)[-dur:] seg1.duration -= dur in_frames = seg2.get_frames(channels=self.channels)[:dur] seg2.start += dur seg2.duration -= dur seg2.comp_location += dur # comp... |
def empty_over_span(self, time, duration): """Helper method that tests whether composition contains any segments at a given time for a given duration. :param time: Time (in seconds) to start span :param duration: Duration (in seconds) of span :returns: `True` if there are no segments in the composition that overlap the... |
def contract(self, time, duration, min_contraction=0.0): """Remove empty gaps from the composition starting at a given time for a given duration. """ # remove audio from the composition starting at time # for duration contract_dur = 0.0 contract_start = time if self.empty_over_span(time, duration): contract_dur = durat... |
and end < time + duration: # does a segment cover the location right before this start? is_key_end = True for seg in self.segments: if seg.comp_location_in_seconds <= end and\ seg.comp_location_in_seconds + seg.duration_in_seconds > end: is_key_end = False break if is_key_end: key_ends.append(end) if len(key_starts) + ... |
for dyn in self.dynamics: if dyn.comp_location_in_seconds > contract_start: dur_samples = int(seg.samplerate * contract_dur) dyn.comp_location -= dur_samples return contract_start, contract_dur else: return 0.0, 0.0 |
def add_music_cue(self, track, comp_cue, song_cue, duration=6.0, padding_before=12.0, padding_after=12.0): """Add a music cue to the composition. This doesn't do any audio analysis, it just aligns a specified point in the track (presumably music) with a location in the composition. See UnderScore_ for a visualization o... |
:param float padding_after: Duration of music playing softly after the music cue/composition cue (in seconds) """ self.tracks.add(track) pre_fade = 3 post_fade = 3 if padding_before + pre_fade > song_cue: padding_before = song_cue - pre_fade if padding_before + pre_fade > score_cue: padding_before = score_cue - pre_fad... |
def build(self, track_list=None, adjust_dynamics=False, min_length=None, channels=None): """ Create a numpy array from the composition. :param track_list: List of tracks to include in composition generation (``None`` means all tracks will be used) :type track_list: list of :py:class:`radiotool.composer.Track` :param in... |
in self.segments if v.track == track], key=lambda k: k.comp_location + k.duration) dyns = sorted([d for d in self.dynamics if d.track == track], key=lambda k: k.comp_location) if len(segments) > 0: start_loc = min([x.comp_location for x in segments]) end_loc = max([x.comp_location + x.duration for x in segments]) if le... |
parts[track][d.comp_location - start_loc : d.comp_location - start_loc + d.duration, :] *= vol_frames if adjust_dynamics: total_energy = RMS_energy(all_frames) song_energy = RMS_energy(song_frames) speech_energy = RMS_energy(speech_frames) # dyn_adj = 0.10 / total_energy # dyn_adj = speech_energy / sqrt(song_energy) * ... |
def export(self, **kwargs): """ Generate audio file from composition. :param str. filename: Output filename (no extension) :param str. filetype: Output file type (only .wav supported for now) :param integer samplerate: Sample rate of output audio :param integer channels: Channels in output audio, if different than orig... |
= 'pcm16' to_mp3 = False if filetype == 'ogg': encoding = 'vorbis' elif filetype == 'mp3': filetype = 'wav' to_mp3 = True if separate_tracks: # build the separate parts of the composition if desired for track in self.tracks: out = self.build(track_list=[track], adjust_dynamics=adjust_dynamics, min_length=min_length, ch... |
xpath + "frameRate", "f%d" % samplerate) for i, lab in enumerate(self.labels): xmp.append_array_item(ns, xpath + "markers", None, array_options={"prop_value_is_array": True}, prop_value_is_struct=True) xmp.set_property(ns, xpath + "markers[%d]/%sname" % (i + 1, p), lab.name) xmp.set_property(ns, xpath + "markers[%d]/%s... |
def get_episode_types(db) -> Iterator[EpisodeType]: """Get all episode types.""" cur = db.cursor() cur.execute('SELECT id, name, prefix FROM episode_type') for type_id, name, prefix in cur: yield EpisodeType(type_id, name, prefix) |
def get_epno(self, episode: Episode): """Return epno for an Episode instance. epno is a string formatted with the episode number and type, e.g., S1, T2. >>> x = EpisodeTypes([EpisodeType(1, 'foo', 'F')]) >>> ep = Episode(type=1, number=2) >>> x.get_epno(ep) 'F2' """ return '{}{}'.format(self[episode.type].prefix, episo... |
def on_discovery_update(self, name, new_config): """ Once a Discovery is updated we update each associated Service to reset its up/down status so that the next iteration of the `check_loop` loop does the proper reporting again. """ for service in self.configurables[Service].values(): if service.discovery == name: servi... |
def on_service_add(self, service): """ When a new service is added, a worker thread is launched to periodically run the checks for that service. """ self.launch_thread(service.name, self.check_loop, service) |
def check_loop(self, service): """ While the reporter is not shutting down and the service being checked is present in the reporter's configuration, this method will launch a job to run all of the service's checks and then pause for the configured interval. """ logger.info("Starting check loop for service '%s'", servic... |
def run_checks(self, service): """ Runs each check for the service and reports to the service's discovery method based on the results. If all checks pass and the service's present node was previously reported as down, the present node is reported as up. Conversely, if any of the checks fail and the service's present no... |
def _do_api_call(self, method, data): """ Convenience method to carry out a standard API call against the Petfinder API. :param basestring method: The API method name to call. :param dict data: Key/value parameters to send to the API method. This varies based on the method. :raises: A number of :py:exc:`petfinder.excep... |
# If this is anything but '100', it's an error. status_code = root.find("header/status/code").text # If this comes back as non-None, we know we've got problems. exc_class = _get_exception_class_from_status_code(status_code) if exc_class: # Sheet, sheet, errar! Raise the appropriate error, and pass # the accompanying er... |
def _do_autopaginating_api_call(self, method, kwargs, parser_func): """ Given an API method, the arguments passed to it, and a function to hand parsing off to, loop through the record sets in the API call until all records have been yielded. This is mostly done this way to reduce duplication through the various API met... |
RecordDoesNotExistError: if not has_records["has_records"]: # No records seen yet, this really is empty. raise # We've seen some records come through. We must have hit the # end of the result set. Finish up silently. return # This is used to track whether this go around the call->parse # loop yielded any records. recor... |
def _parse_datetime_str(self, dtime_str): """ Given a standard datetime string (as seen throughout the Petfinder API), spit out the corresponding UTC datetime instance. :param str dtime_str: The datetime string to parse. :rtype: datetime.datetime :returns: The parsed datetime. """ return datetime.datetime.strptime( dti... |
def _parse_pet_record(self, root): """ Given a <pet> Element from a pet.get or pet.getRandom response, pluck out the pet record. :param lxml.etree._Element root: A <pet> tag Element. :rtype: dict :returns: An assembled pet record. """ record = { "breeds": [], "photos": [], "options": [], "contact": {}, } # These fields... |
Find all of the <breed> tags and # stuff their text (breed names) into the record. for breed in root.findall("breeds/breed"): record["breeds"].append(breed.text) # We'll deviate slightly from the XML format here, and simply append # each photo entry to the record's "photo" key. for photo in root.findall("media/photos/p... |
def breed_list(self, **kwargs): """ breed.list wrapper. Returns a list of breed name strings. :rtype: list :returns: A list of breed names. """ root = self._do_api_call("breed.list", kwargs) breeds = [] for breed in root.find("breeds"): breeds.append(breed.text) return breeds |
def pet_get(self, **kwargs): """ pet.get wrapper. Returns a record dict for the requested pet. :rtype: dict :returns: The pet's record dict. """ root = self._do_api_call("pet.get", kwargs) return self._parse_pet_record(root.find("pet")) |
def pet_getrandom(self, **kwargs): """ pet.getRandom wrapper. Returns a record dict or Petfinder ID for a random pet. :rtype: dict or str :returns: A dict of pet data if ``output`` is ``'basic'`` or ``'full'``, and a string if ``output`` is ``'id'``. """ root = self._do_api_call("pet.getRandom", kwargs) output_brevity ... |
def pet_find(self, **kwargs): """ pet.find wrapper. Returns a generator of pet record dicts matching your search criteria. :rtype: generator :returns: A generator of pet record dicts. :raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have reached the maximum number of records your credentials allow you to ... |
def shelter_find(self, **kwargs): """ shelter.find wrapper. Returns a generator of shelter record dicts matching your search criteria. :rtype: generator :returns: A generator of shelter record dicts. :raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have reached the maximum number of records your credentia... |
def shelter_get(self, **kwargs): """ shelter.get wrapper. Given a shelter ID, retrieve its details in dict form. :rtype: dict :returns: The shelter's details. """ root = self._do_api_call("shelter.get", kwargs) shelter = root.find("shelter") for field in shelter: record = {} for field in shelter: record[field.tag] = fi... |
def shelter_getpets(self, **kwargs): """ shelter.getPets wrapper. Given a shelter ID, retrieve either a list of pet IDs (if ``output`` is ``'id'``), or a generator of pet record dicts (if ``output`` is ``'full'`` or ``'basic'``). :rtype: generator :returns: Either a generator of pet ID strings or pet record dicts, depe... |
shelter_getpets_parser_records return self._do_autopaginating_api_call( "shelter.getPets", kwargs, shelter_getpets_parser ) |
def shelter_listbybreed(self, **kwargs): """ shelter.listByBreed wrapper. Given a breed and an animal type, list the shelter IDs with pets of said breed. :rtype: generator :returns: A generator of shelter IDs that have breed matches. """ root = self._do_api_call("shelter.listByBreed", kwargs) shelter_ids = root.findall... |
def add_callback(self, event, cb, args=None): '''Add a callback to this node. Callbacks are called when the specified event occurs. The available events depends on the specific node type. Args should be a value to pass to the callback when it is called. The callback should be of the format: def callback(node, value, cb... |
def get_node(self, path): '''Get a child node of this node, or this node, based on a path. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return The node pointed to by @ref path, or None if the ... |
None else: return None |
def has_path(self, path): '''Check if a path exists below this node. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return True if the path points to a node in the tree below this node, or this ... |
def iterate(self, func, args=None, filter=[]): '''Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref args. @para... |
@ref func in a list. Example: >>> c1 = TreeNode(name='c1') >>> c2 = TreeNode(name='c2') >>> p = TreeNode(name='p', children={'c1':c1, 'c2':c2}) >>> c1._parent = p >>> c2._parent = p >>> def hello(n, args): ... return args[0] + ' ' + n._name >>> p.iterate(hello, args=['hello']) ['hello p', 'hello c2', 'hello c1'] >>> p.... |
def rem_callback(self, event, cb): '''Remove a callback from this node. The callback is removed from the specified event. @param cb The callback function to remove. ''' if event not in self._cbs: raise exceptions.NoSuchEventError(self.name, event) c = [(x[0], x[1]) for x in self._cbs[event]] if not c: raise exceptions.... |
def full_path(self): '''The full path of this node.''' with self._mutex: if self._parent: return self._parent.full_path + [self._name] else: return [self._name] |
def full_path_str(self): '''The full path of this node as a string.''' with self._mutex: if self._parent: if self._parent._name == '/': return self._parent.full_path_str + self._name else: return self._parent.full_path_str + '/' + self._name else: return self._name |
def nameserver(self): '''The name server of the node (i.e. its top-most parent below /).''' with self._mutex: if not self._parent: # The root node does not have a name server return None elif self._parent.name == '/': return self else: return self._parent.nameserver |
def orb(self): '''The ORB used to access this object. This property's value will be None if no object above this object is a name server. ''' with self._mutex: if self._parent.name == '/': return None return self._parent.orb |
def root(self): '''The root node of the tree this node is in.''' with self._mutex: if self._parent: return self._parent.root else: return self |
def command(state, args): """Delete priority rule.""" args = parser.parse_args(args[1:]) query.files.delete_priority_rule(state.db, args.id) del state.file_picker |
def upsert(db, table, key_cols, update_dict): """Fabled upsert for SQLiteDB. Perform an upsert based on primary key. :param SQLiteDB db: database :param str table: table to upsert into :param str key_cols: name of key columns :param dict update_dict: key-value pairs to upsert """ with db: cur = db.cursor() cur.execute(... |
def command(state, args): """Add an anime from an AniDB search.""" if len(args) < 2: print(f'Usage: {args[0]} {{ID|aid:AID}}') return aid = state.results.parse_aid(args[1], default_key='anidb') anime = request_anime(aid) query.update.add(state.db, anime) |
def Ode(self, z): """ Returns the sum of :func:`~classylss.binding.Background.Omega_lambda` and :func:`~classylss.binding.Background.Omega_fld`. """ return self.bg.Omega_lambda(z) + self.bg.Omega_fld(z) |
def Onu(self, z): """ Returns the sum of :func:`~classylss.binding.Background.Omega_ncdm` and :func:`~classylss.binding.Background.Omega_ur`. """ return self.bg.Omega_ncdm(z) + self.bg.Omega_ur(z) |
def current(cls, service, port): """ Returns a Node instance representing the current service node. Collects the host and IP information for the current machine and the port information from the given service. """ host = socket.getfqdn() return cls( host=host, ip=socket.gethostbyname(host), port=port, metadata=service.... |
def serialize(self): """ Serializes the node data as a JSON map string. """ return json.dumps({ "port": self.port, "ip": self.ip, "host": self.host, "peer": self.peer.serialize() if self.peer else None, "metadata": json.dumps(self.metadata or {}, sort_keys=True), }, sort_keys=True) |
def deserialize(cls, value): """ Creates a new Node instance via a JSON map string. Note that `port` and `ip` and are required keys for the JSON map, `peer` and `host` are optional. If `peer` is not present, the new Node instance will use the current peer. If `host` is not present, the hostname of the given `ip` is loo... |
peer=peer, metadata=parsed.get("metadata") ) |
def start(self): """ Iterates over the `watched_configurabes` attribute and starts a config file monitor for each. The resulting observer threads are kept in an `observers` list attribute. """ for config_class in self.watched_configurables: monitor = ConfigFileMonitor(config_class, self.config_dir) self.observers.appen... |
def launch_thread(self, name, fn, *args, **kwargs): """ Adds a named thread to the "thread pool" dictionary of Thread objects. A daemon thread that executes the passed-in function `fn` with the given args and keyword args is started and tracked in the `thread_pool` attribute with the given `name` as the key. """ logger... |
def kill_thread(self, name): """ Joins the thread in the `thread_pool` dict with the given `name` key. """ if name not in self.thread_pool: return self.thread_pool[name].join() del self.thread_pool[name] |
def update_configurable(self, configurable_class, name, config): """ Callback fired when a configurable instance is updated. Looks up the existing configurable in the proper "registry" and `apply_config()` is called on it. If a method named "on_<configurable classname>_update" is defined it is called in the work pool a... |
def remove_configurable(self, configurable_class, name): """ Callback fired when a configurable instance is removed. Looks up the existing configurable in the proper "registry" and removes it. If a method named "on_<configurable classname>_remove" is defined it is called via the work pooland passed the configurable's n... |
def hook_for(self, configurable_class, action): """ Helper method for determining if an on_<configurable class>_<action> method is present, to be used as a hook in the add/update/remove configurable methods. """ configurable_class_name = configurable_class.__name__.lower() return getattr( self, "on_" + configurable_cla... |
def stop(self): """ Method for shutting down the watcher. All config file observers are stopped and their threads joined, along with the worker thread pool. """ self.shutdown.set() for monitor in self.observers: monitor.stop() self.wind_down() for monitor in self.observers: monitor.join() for thread in self.thread_pool... |
def set_attributes(self, **kwargs): """ Set the resource attributes from the kwargs. Only sets items in the `self.Meta.attributes` white list. Subclass this method to customise attributes. Args: kwargs: Keyword arguements passed into the init of this class """ if self._subresource_map: self.set_subresources(**kwargs) f... |
def get_resource_url(cls, resource, base_url): """ Construct the URL for talking to this resource. i.e.: http://myapi.com/api/resource Note that this is NOT the method for calling individual instances i.e. http://myapi.com/api/resource/1 Args: resource: The resource class instance base_url: The Base URL of this API ser... |
def get_url(cls, url, uid, **kwargs): """ Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additional keyword argueents returns: final_url: The URL for this individual resource """ ... |
def get_method_name(resource, method_type): """ Generate a method name for this resource based on the method type. """ return '{}_{}'.format(method_type.lower(), resource.Meta.name.lower()) |
def _parse_url_and_validate(cls, url): """ Recieves a URL string and validates it using urlparse. Args: url: A URL string Returns: parsed_url: A validated URL Raises: BadURLException """ parsed_url = urlparse(url) if parsed_url.scheme and parsed_url.netloc: final_url = parsed_url.geturl() else: raise BadURLException re... |
def set_related_method(self, resource, full_resource_url): """ Using reflection, generate the related method and return it. """ method_name = self.get_method_name(resource, 'get') def get(self, **kwargs): return self._call_api_single_related_resource( resource, full_resource_url, method_name, **kwargs ) def get_list(se... |
def match_urls_to_resources(self, url_values): """ For the list of valid URLs, try and match them up to resources in the related_resources attribute. Args: url_values: A dictionary of keys and URL strings that could be related resources. Returns: valid_values: The values that are valid """ valid_values = {} for resourc... |
def set_attributes(self, **kwargs): """ Similar to BaseResource.set_attributes except it will attempt to match URL strings with registered related resources, and build their get_* method and attach it to this resource. """ if not self.Meta.related_resources: # Just do what the normal BaseResource does super(HypermediaR... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.