code
stringlengths
1
18.2k
def delete(self, *args, **kwargs): """ Delete clonable relations first, since they may be objects that wouldn't otherwise be deleted. Calls super to actually delete the object. """ skip_reverses = kwargs.pop('skip_reverses', False) if not skip_reverses: self._delete_reverses() return super(Cloneable, self).delete(*args...
def save(self, *args, **kwargs): """ Takes an optional last_save keyword argument other wise last_save will be set to timezone.now() Calls super to actually save the object. """ self.last_save = kwargs.pop('last_save', timezone.now()) super(Cloneable, self).save(*args, **kwargs)
def register_related(cls, related_name): """ Register a related item that should be cloned when this model is. :param related_name: Use the name you would use in filtering i.e.: book not book_set. """ if not hasattr(cls, '_clone_related'): cls._clone_related = [] if type(cls._clone_related) != type([]): cls._clone_rela...
def add_to_class(cls, name, value): """ Django 1.10 doesn't allow us to modify `_base_manager` attr: https://docs.djangoproject.com/en/1.10/topics/db/managers/#django.db.models.Model._base_manager """ if name == '_base_manager': if not value.name: value.name = name value.model = cls setattr(cls._meta, 'base_manager_nam...
def get_version(self, state=None, date=None): """ Get a particular version of an item :param state: The state you want to get. :param date: Get a version that was published before or on this date. """ version_model = self._meta._version_model q = version_model.objects.filter(object_id=self.pk) if state: q = version_mod...
def unpublish(self): """ Unpublish this item. This will set and currently published versions to the archived state and delete all currently scheduled versions. """ assert self.state == self.DRAFT with xact(): self._publish(published=False) # Delete all scheduled items klass = self.get_version_class() for obj in klass.n...
def publish(self, user=None, when=None): """ Publishes a item and any sub items. A new transaction will be started if we aren't already in a transaction. Should only be run on draft items """ assert self.state == self.DRAFT user_published = 'code' if user: user_published = user.username now = timezone.now() with xact()...
cloned this if self.state == self.DRAFT: self.last_scheduled = now self.date_published = when self.save(last_save=now) self._clone() self.user_published = user_published self.state = self.SCHEDULED self.save() self.schedule(when=when)
def make_draft(self): """ Make this version the draft """ assert self.__class__ == self.get_version_class() # If this is draft do nothing if self.state == self.DRAFT: return with xact(): # Delete whatever is currently this draft try: klass = self.get_version_class() old_draft = klass.normal.get(object_id=self.object_id...
def purge_archives(self): """ Delete older archived items. Use the class attribute NUM_KEEP_ARCHIVED to control how many items are kept. """ klass = self.get_version_class() qs = klass.normal.filter(object_id=self.object_id, state=self.ARCHIVED).order_by('-last_save')[self.NUM_KEEP_ARCHIVED:] for obj in qs: obj._delete...
def status_line(self): """ Returns a status line for an item. Only really interesting when called for a draft item as it can tell you if the draft is the same as another version. """ date = self.date_published status = self.state.title() if self.state == self.DRAFT: # Check if this item has changed since # our last pub...
if self.last_scheduled >= self.v_last_save: status = self.PUBLISHED.title() # The date this was scheduled is greater than # what is currently live, this will go live at # some point if self.last_scheduled > self.v_last_save: status = "Publish Scheduled" else: status = "Publish Scheduled" date = self.date_published if d...
def schedule(self, when=None, action=None, **kwargs): """ Schedule this item to be published. :param when: Date/time when this item should go live. None means now. """ action = '_publish' super(BaseVersionedModel, self).schedule(when=when, action=action, **kwargs)
def validate_unique(self, *args, **kwargs): """ Calls super validate_unique and, after that is done, runs through any field_names listed in `self.versioned_unique` and checks that this is the only item with this name. This relies on using the public schema when running this check. These checks contain race conditions s...
def validate_unique(self, *args, **kwargs): """ Calls super validate_unique and, after that is done, runs through any field_names listed in `self.versioned_unique` and checks that this is the only item with this name. These checks contain race conditions since it all happens before saves and so should not be relied upo...
def save(self, *args, **kwargs): """ Saves this item. Creates a default base if there isn't one already. """ with xact(): if not self.vid: self.state = self.DRAFT if not self.object_id: base = self._meta._base_model(is_published=False) base.save(*args, **kwargs) self.object = base super(VersionModel, self).save(*args, ...
def slugify(text, delim='-'): """Generate an ASCII-only slug.""" result = [] for word in _punct_re.split((text or '').lower()): result.extend(codecs.encode(word, 'ascii', 'replace').split()) return delim.join([str(r) for r in result])
def parser(): """Return search query parser.""" query_parser = current_app.config['COLLECTIONS_QUERY_PARSER'] if isinstance(query_parser, six.string_types): query_parser = import_string(query_parser) return query_parser
def query_walkers(): """Return query walker instances.""" return [ import_string(walker)() if isinstance(walker, six.string_types) else walker() for walker in current_app.config[ 'COLLECTIONS_QUERY_WALKERS'] ]
def pad(cls, data): """ Pads data to match AES block size """ if sys.version_info > (3, 0): try: data = data.encode("utf-8") except AttributeError: pass length = AES.block_size - (len(data) % AES.block_size) data += bytes([length]) * length return data else: return data + (AES.block_size - len(data) % AES.block_size) *...
def unpad(cls, data): """ Unpads data that has been padded """ if sys.version_info > (3, 0): return data[:-ord(data[len(data)-1:])].decode() else: return data[:-ord(data[len(data)-1:])]
def encrypt(self, raw): """ Encrypts raw data using AES and then base64 encodes it. :param raw: :return: """ padded = AESCipher.pad(raw) init_vec = Random.new().read(AES.block_size) cipher = AES.new(self._key, AES.MODE_CBC, init_vec) return b64encode(init_vec + cipher.encrypt(padded))
def decrypt(self, encrypted): """ Base64 decodes the data and then decrypts using AES. :param encrypted: :return: """ decoded = b64decode(encrypted) init_vec = decoded[:AES.block_size] cipher = AES.new(self._key, AES.MODE_CBC, init_vec) return AESCipher.unpad(cipher.decrypt(decoded[AES.block_size:]))
def simple_locking(lock_id, expiration=None): """ A decorator that wraps a function in a single lock getting algorithm """ def inner_decorator(function): def wrapper(*args, **kwargs): try: # Trying to acquire lock lock = Lock.acquire_lock(lock_id, expiration) except LockError: # Unable to acquire lock - non fatal pass ...
def fix(source_key, rownum, line, source, sample_only_filter, sample_size): """ :param rownum: :param line: :param source: :param sample_only_filter: :param sample_size: :return: (row, no_more_data) TUPLE WHERE row IS {"value":<data structure>} OR {"json":<text line>} """ value = json2value(line) if rownum == 0: if len...
def copy(self, keys, source, sample_only_filter=None, sample_size=None, done_copy=None): """ :param keys: THE KEYS TO LOAD FROM source :param source: THE SOURCE (USUALLY S3 BUCKET) :param sample_only_filter: SOME FILTER, IN CASE YOU DO NOT WANT TO SEND EVERYTHING :param sample_size: FOR RANDOM SAMPLE OF THE source DATA...
= fix(key, rownum, line, source, sample_only_filter, sample_size) if insert_me == None: continue value = insert_me['value'] if '_id' not in value: Log.warning("expecting an _id in all S3 records. If missing, there can be duplicates") if queue == None: queue = self._get_queue(insert_me) if queue == None: pending.append(...
not process {{key}} after {{duration|round(places=2)}}seconds", key=key, duration=timer.duration.seconds, cause=e) done_copy = None if done_copy: if queue == None: done_copy() elif queue is DATA_TOO_OLD: done_copy() else: queue.add(done_copy) if [p for p in pending if wrap(p).value.task.state not in ('failed', 'excepti...
def from_env(): """Get host/port settings from the environment.""" if 'MICROMONGO_URI' in os.environ: return (os.environ['MICROMONGO_URI'],) host = os.environ.get('MICROMONGO_HOST', 'localhost') port = int(os.environ.get('MICROMONGO_PORT', 27017)) return (host, port)
def order_by(self, *fields): """An alternate to ``sort`` which allows you to specify a list of fields and use a leading - (minus) to specify DESCENDING.""" doc = [] for field in fields: if field.startswith('-'): doc.append((field.strip('-'), pymongo.DESCENDING)) else: doc.append((field, pymongo.ASCENDING)) return self....
def next(self): """A `next` that caches the returned results. Together with the slightly different `__iter__`, these cursors can be iterated over more than once.""" if self.__tailable: return PymongoCursor.next(self) try: ret = PymongoCursor.next(self) except StopIteration: self.__fullcache = True raise self.__itercach...
def _strip_dollars_fast(text): """ Replace `$$` with `$`. raise immediately if `$` starting an interpolated expression is found. @param text: the source text @return: the text with dollars replaced, or raise HasExprException if there are interpolated expressions """ def _sub(m): if m.group(0) == '$$': return '$' raise ...
def adjust_locations(ast_node, first_lineno, first_offset): """ Adjust the locations of the ast nodes, offsetting them to the new lineno and column offset """ line_delta = first_lineno - 1 def _fix(node): if 'lineno' in node._attributes: lineno = node.lineno col = node.col_offset # adjust the offset on the first line i...
def coalesce_outputs(tree): """ Coalesce the constant output expressions __output__('foo') __output__('bar') __output__(baz) __output__('xyzzy') into __output__('foobar', baz, 'xyzzy') """ coalesce_all_outputs = True if coalesce_all_outputs: should_coalesce = lambda n: True else: should_coalesce = lambda n: n.output_ar...
""" if not ast_equals(node.func, NameX('__TK__output')): return for i in range(len(node.args)): arg1 = node.args[i] if not arg1.__class__.__name__ == 'Call': continue if not ast_equals(arg1.func, NameX('__TK__escape')): continue if len(arg1.args) != 1: continue arg2 = arg1.args[0] if not arg2.__class__.__name__ == 'Cal...
def remove_locations(node): """ Removes locations from the given AST tree completely """ def fix(node): if 'lineno' in node._attributes and hasattr(node, 'lineno'): del node.lineno if 'col_offset' in node._attributes and hasattr(node, 'col_offset'): del node.col_offset for child in iter_child_nodes(node): fix(child) fi...
def dataReceived(self, data): """ 当数据接受到时 :param data: :return: """ self._read_buffer += data while self._read_buffer: # 因为box后面还是要用的 box = self.factory.app.box_class() ret = box.unpack(self._read_buffer) if ret == 0: # 说明要继续收 return elif ret > 0: # 收好了 box_data = self._read_buffer[:ret] self._read_buffer = self._read_...
def _on_read_complete(self, data, box): """ 完整数据接收完成 :param data: 原始数据 :param box: 解析之后的box :return: """ msg = dict( conn_id=id(self), address=self.address, data=data, ) # 获取映射的group_id group_id = self.factory.app.group_router(box) try: self.factory.app.parent_output_dict[group_id].put_nowait(msg) except: logger.error(...
def pop(self, timeout=None): """ :param timeout: OPTIONAL DURATION :return: None, IF timeout PASSES """ with self.lock: while not self.please_stop: if self.db.status.end > self.start: value = self.db[str(self.start)] self.start += 1 return value if timeout is not None: with suppress_exception: self.lock.wait(timeout=ti...
def pop_all(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ with self.lock: if self.please_stop: return [THREAD_STOP] if self.db.status.end == self.start: return [] output = [] for i in range(self.start, self.db.status.end): output.append(self.db[str(i)]) self.start = self.db.status.end return output
def rows_to_columns(data, schema=None): """ :param data: array of objects :param schema: Known schema, will be extended to include all properties found in data :return: Table """ if not schema: schema = SchemaTree() all_schema = schema all_leaves = schema.leaves values = {full_name: [] for full_name in all_leaves} reps...
DEFAULT TO REQUIRED ENTRIES new_schema = schema schema.element.repetition_type = REQUIRED else: new_path = path new_value = value[0] ptype = type(new_value) new_schema = schema.add( new_path, OPTIONAL, ptype ) if new_value is None or python_type_to_json_type[ptype] in PRIMITIVE: values[new_path] = [] reps[new_path] = [...
sub_schema, new_path, counters, new_def_level) for name in set(value.keys()) - set(schema.more.keys()): if schema.locked: Log.error("{{path}} is not allowed in the schema", path=path) new_path = concat_field(path, name) new_value = value.get(name, None) ptype = type(new_value) sub_schema = schema.add( new_path, REPEATE...
def from_content(cls, content): """Creates an instance of the class from the html content of the character's page. Parameters ---------- content: :class:`str` The HTML content of the page. Returns ------- :class:`Character` The character contained in the page, or None if the character doesn't exist Raises ------ Invali...
def from_tibiadata(cls, content): """Builds a character object from a TibiaData character response. Parameters ---------- content: :class:`str` The JSON content of the response. Returns ------- :class:`Character` The character contained in the page, or None if the character doesn't exist Raises ------ InvalidContent If...
= character_data.get("Position:") if "guild" in character_data: char.guild_membership = GuildMembership(character_data["guild"]["name"], character_data["guild"]["rank"]) if "house" in character_data: house = character_data["house"] paid_until_date = parse_tibiadata_date(house["paid"]) char.house = CharacterHouse(house[...
def _parse_account_information(self, rows): """ Parses the character's account information Parameters ---------- rows: :class:`list` of :class:`bs4.Tag`, optional A list of all rows contained in the table. """ acc_info = {} if not rows: return for row in rows: cols_raw = row.find_all('td') cols = [ele.text.strip() for ...
def _parse_achievements(self, rows): """ Parses the character's displayed achievements Parameters ---------- rows: :class:`list` of :class:`bs4.Tag` A list of all rows contained in the table. """ for row in rows: cols = row.find_all('td') if len(cols) != 2: continue field, value = cols grade = str(field).count("achieve...
def _parse_character_information(self, rows): """ Parses the character's basic information and applies the found values. Parameters ---------- rows: :class:`list` of :class:`bs4.Tag` A list of all rows contained in the table. """ int_rows = ["level", "achievement_points"] char = {} house = {} for row in rows: cols_raw ...
the character is deleted, the information is fouund with the name, so we must clean it m = deleted_regexp.match(char["name"]) if m: char["name"] = m.group(1) char["deletion_date"] = parse_tibia_datetime(m.group(2)) if "guild_membership" in char: m = guild_regexp.match(char["guild_membership"]) char["guild_membership"] ...
def _parse_deaths(self, rows): """ Parses the character's recent deaths Parameters ---------- rows: :class:`list` of :class:`bs4.Tag` A list of all rows contained in the table. """ for row in rows: cols = row.find_all('td') death_time_str = cols[0].text.replace("\xa0", " ").strip() death_time = parse_tibia_datetime(dea...
except ValueError: # Some pvp deaths have no level, so they are raising a ValueError, they will be ignored for now. continue
def _parse_killer(cls, killer): """Parses a killer into a dictionary. Parameters ---------- killer: :class:`str` The killer's raw HTML string. Returns ------- :class:`dict`: A dictionary containing the killer's info. """ # If the killer contains a link, it is a player. if "href" in killer: killer_dict = {"name": link_c...
def _parse_other_characters(self, rows): """ Parses the character's other visible characters. Parameters ---------- rows: :class:`list` of :class:`bs4.Tag` A list of all rows contained in the table. """ for row in rows: cols_raw = row.find_all('td') cols = [ele.text.strip() for ele in cols_raw] if len(cols) != 5: conti...
def _parse_tables(cls, parsed_content): """ Parses the information tables contained in a character's page. Parameters ---------- parsed_content: :class:`bs4.BeautifulSoup` A :class:`BeautifulSoup` object containing all the content. Returns ------- :class:`OrderedDict`[str, :class:`list`of :class:`bs4.Tag`] A dictionary...
def _split_list(cls, items, separator=",", last_separator=" and "): """ Splits a string listing elements into an actual list. Parameters ---------- items: :class:`str` A string listing elements. separator: :class:`str` The separator between each item. A comma by default. last_separator: :class:`str` The separator used ...
def by_player(self): """:class:`bool`: Whether the kill involves other characters.""" return any([k.player and self.name != k.name for k in self.killers])
def create_many_to_many_intermediary_model(field, klass): """ Copied from django, but uses FKToVersion for the 'from' field. Fields are also always called 'from' and 'to' to avoid problems between version combined models. """ managed = True if (isinstance(field.remote_field.to, basestring) and field.remote_field.to != ...
to.lower() meta = type('Meta', (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'managed': managed, 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': ('from', 'to'), 'verbose_name': '%(from)s-%(to)s relationship' % { 'from': from_, 't...
def deconstruct(self): """ FK to version always points to a version table """ name, path, args, kwargs = super(FKToVersion, self).deconstruct() if not kwargs['to'].endswith('_version'): kwargs['to'] = '{0}_version'.format(kwargs['to']) return name, path, args, kwargs
def update_rel_to(self, klass): """ If we have a string for a model, see if we know about it yet, if so use it directly otherwise take the lazy approach. This check is needed because this is called before the main M2M field contribute to class is called. """ if isinstance(self.remote_field.to, basestring): relation = s...
def contribute_to_class(self, cls, name): """ Because django doesn't give us a nice way to provide a through table without losing functionality. We have to provide our own through table creation that uses the FKToVersion field to be used for the from field. """ self.update_rel_to(cls) # Called to get a name self.set_at...
def notCalled(cls, spy): #pylint: disable=invalid-name """ Checking the inspector is not called Args: SinonSpy """ cls.__is_spy(spy) if not (not spy.called): raise cls.failException(cls.message)
def calledOnce(cls, spy): #pylint: disable=invalid-name """ Checking the inspector is called once Args: SinonSpy """ cls.__is_spy(spy) if not (spy.calledOnce): raise cls.failException(cls.message)
def calledTwice(cls, spy): #pylint: disable=invalid-name """ Checking the inspector is called twice Args: SinonSpy """ cls.__is_spy(spy) if not (spy.calledTwice): raise cls.failException(cls.message)
def calledThrice(cls, spy): #pylint: disable=invalid-name """ Checking the inspector is called thrice Args: SinonSpy """ cls.__is_spy(spy) if not (spy.calledThrice): raise cls.failException(cls.message)
def callCount(cls, spy, number): #pylint: disable=invalid-name """ Checking the inspector is called number times Args: SinonSpy, number """ cls.__is_spy(spy) if not (spy.callCount == number): raise cls.failException(cls.message)
def callOrder(cls, *args): #pylint: disable=invalid-name """ Checking the inspector is called with given priority Args: SinonSpy, list of inspectors eg. [spy1, spy2, spy3] => spy1 is called before spy2, spy2 is called before spy3 [spy1, spy2, spy1] => spy1 is called before and after spy2 """ for spy in args: cls.__is_s...
def calledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is called with partial args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.calledWith(*args, **kwargs)): raise cls.failException(cls.message)
def alwaysCalledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is always called with partial args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.alwaysCalledWith(*args, **kwargs)): raise cls.failException(cls.message)
def neverCalledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is never called with partial args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.neverCalledWith(*args, **kwargs)): raise cls.failException(cls.message)
def calledWithExactly(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is called with exactly args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.calledWithExactly(*args, **kwargs)): raise cls.failException(cls.message)
def alwaysCalledWithExactly(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is always called with exactly args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.alwaysCalledWithExactly(*args, **kwargs)): raise cls.failException(cls.message)
def calledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is called with partial SinonMatcher(args/kwargs) Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.calledWithMatch(*args, **kwargs)): raise cls.failException(cls.message)
def alwaysCalledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is always called with partial SinonMatcher(args/kwargs) Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.alwaysCalledWithMatch(*args, **kwargs)): raise cls.failException(cls.message)
def neverCalledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is never called with partial SinonMatcher(args/kwargs) Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.neverCalledWithMatch(*args, **kwargs)): raise cls.failException(cls.message)
def threw(cls, spy, error_type=None): """ Checking the inspector is raised error_type Args: SinonSpy, Exception (defaut: None) """ cls.__is_spy(spy) if not (spy.threw(error_type)): raise cls.failException(cls.message)
def alwaysThrew(cls, spy, error_type=None): #pylint: disable=invalid-name """ Checking the inspector is always raised error_type Args: SinonSpy, Exception (defaut: None) """ cls.__is_spy(spy) if not (spy.alwaysThrew(error_type)): raise cls.failException(cls.message)
def _scrub_key(key): """ RETURN JUST THE :. CHARACTERS """ if key == None: return None output = [] for c in key: if c in [":", "."]: output.append(c) return "".join(output)
def get_meta(self, key, conforming=True): """ RETURN METADATA ON FILE IN BUCKET :param key: KEY, OR PREFIX OF KEY :param conforming: TEST IF THE KEY CONFORMS TO REQUIRED PATTERN :return: METADATA, IF UNIQUE, ELSE ERROR """ try: metas = list(self.bucket.list(prefix=key)) metas = wrap([m for m in metas if m.name.find(".j...
not perfect and error: Log.error("Problem with key request", error) return coalesce(perfect, favorite) except Exception as e: Log.error(READ_ERROR+" can not read {{key}} from {{bucket}}", key=key, bucket=self.bucket.name, cause=e)
def keys(self, prefix=None, delimiter=None): """ :param prefix: NOT A STRING PREFIX, RATHER PATH ID PREFIX (MUST MATCH TO NEXT "." OR ":") :param delimiter: TO GET Prefix OBJECTS, RATHER THAN WHOLE KEYS :return: SET OF KEYS IN BUCKET, OR """ if delimiter: # WE REALLY DO NOT GET KEYS, BUT RATHER Prefix OBJECTS # AT LEAS...
def metas(self, prefix=None, limit=None, delimiter=None): """ RETURN THE METADATA DESCRIPTORS FOR EACH KEY """ limit = coalesce(limit, TOO_MANY_KEYS) keys = self.bucket.list(prefix=prefix, delimiter=delimiter) prefix_len = len(prefix) output = [] for i, k in enumerate(k for k in keys if len(k.key) == prefix_len or k.ke...
def make_middleware(app=None, *args, **kw): """ Given an app, return that app wrapped in RaptorizeMiddleware """ app = RaptorizeMiddleware(app, *args, **kw) return app
def should_raptorize(self, req, resp): """ Determine if this request should be raptorized. Boolean. """ if resp.status != "200 OK": return False content_type = resp.headers.get('Content-Type', 'text/plain').lower() if not 'html' in content_type: return False if random.random() > self.random_chance: return False if self...
def raptorize(self, resp): """ Raptorize this response! Insert javascript into the <head> tag. If jquery is already included, make sure not to stomp on it by re-including it. """ soup = BeautifulSoup.BeautifulSoup(resp.body) if not soup.html: return resp if not soup.html.head: soup.html.insert(0, BeautifulSoup.Tag(soup...
def bind(context, block=False): """ Given the context, returns a decorator wrapper; the binder replaces the wrapped func with the value from the context OR puts this function in the context with the name. """ if block: def decorate(func): name = func.__name__.replace('__TK__block__', '') if name not in context: context...
def override(func): """ THIS DECORATOR WILL PUT ALL PARAMETERS INTO THE `kwargs` PARAMETER AND THEN PUT ALL `kwargs` PARAMETERS INTO THE FUNCTION PARAMETERS. THIS HAS THE BENEFIT OF HAVING ALL PARAMETERS IN ONE PLACE (kwargs), PLUS ALL PARAMETERS ARE EXPLICIT FOR CLARITY. OF COURSE, THIS MEANS PARAMETER ASSIGNMENT MAY ...
at least" in err or "required positional argument" in err): missing = [p for p in params if str(p) not in packed] given = [p for p in params if str(p) in packed] if not missing: raise e else: get_logger().error( "Problem calling {{func_name}}: Expecting parameter {{missing}}, given {{given}}", func_name=func_name, miss...
len(kwargs) == 0 and is_data(args[1]): # ASSUME SECOND UNNAMED PARAM IS kwargs packed = params_pack(params, args[1], defaults) else: # DO NOT INCLUDE self IN kwargs packed = params_pack(params, dict_zip(params[1:], args[1:]), kwargs, defaults) try: return func(args[0], **packed) except TypeError as e: packed['self'] = ...
1 and len(kwargs) == 0 and is_data(args[0]): # ASSUME SINGLE PARAMETER IS kwargs packed = params_pack(params, args[0], defaults) elif "kwargs" in kwargs and is_data(kwargs["kwargs"]): # PUT args INTO kwargs packed = params_pack(params, kwargs, dict_zip(params, args), kwargs["kwargs"], defaults) else: # PULL kwargs OUT ...
def build_homogeneisation_vehicules(temporary_store = None, year = None): assert temporary_store is not None """Compute vehicule numbers by type""" assert year is not None # Load data bdf_survey_collection = SurveyCollection.load( collection = 'budget_des_familles', config_files_directory = config_files_directory) surv...
vehicule.index = vehicule.index.astype(ident_men_dtype) if year == 2005: vehicule = survey.get_values(table = "automobile") kept_variables = ['ident_men', 'carbu'] vehicule = vehicule[kept_variables] vehicule["veh_tot"] = 1 vehicule["veh_essence"] = (vehicule['carbu'] == 1) vehicule["veh_diesel"] = (vehicule['carbu'] =...
def request(method, url, headers=None, zip=None, retry=None, **kwargs): """ JUST LIKE requests.request() BUT WITH DEFAULT HEADERS AND FIXES DEMANDS data IS ONE OF: * A JSON-SERIALIZABLE STRUCTURE, OR * LIST OF JSON-SERIALIZABLE STRUCTURES, OR * None Parameters * zip - ZIP THE REQUEST BODY, IF BIG ENOUGH * json - JSON-S...
"function to set `pyLibrary.env.http.default_headers`" )) _warning_sent = True if is_list(url): # TRY MANY URLS failures = [] for remaining, u in jx.countdown(url): try: response = request(method, u, retry=retry, **kwargs) if mo_math.round(response.status_code, decimal=-2) not in [400, 500]: return response if not rema...
= retry.sleep.seconds del kwargs['retry'] # JSON if 'json' in kwargs: kwargs['data'] = value2json(kwargs['json']).encode('utf8') del kwargs['json'] # ZIP set_default(headers, {'Accept-Encoding': 'compress, gzip'}) if kwargs['zip'] and len(coalesce(kwargs.get('data'))) > 1000: compressed = convert.bytes2zip(kwargs['data...
times=retry.times, cause=errors[0]) else: Log.error(u"Tried {{times}} times: Request failure of {{url}}", url=url, times=retry.times, cause=errors[0])
def get_json(url, **kwargs): """ ASSUME RESPONSE IN IN JSON """ response = get(url, **kwargs) try: c = response.all_content return json2value(utf82unicode(c)) except Exception as e: if mo_math.round(response.status_code, decimal=-2) in [400, 500]: Log.error(u"Bad GET response: {{code}}", code=response.status_code) else...
def post_json(url, **kwargs): """ ASSUME RESPONSE IN IN JSON """ if 'json' in kwargs: kwargs['data'] = unicode2utf8(value2json(kwargs['json'])) del kwargs['json'] elif 'data' in kwargs: kwargs['data'] = unicode2utf8(value2json(kwargs['data'])) else: Log.error(u"Expecting `json` parameter") response = post(url, **kwargs...
def get_projects_list(self): """ Get projects list """ try: result = self._request('/getprojectslist/') return [TildaProject(**p) for p in result] except NetworkError: return []