code
stringlengths
1
18.2k
def dump_element(element): """ Dumps the content of the given ElementBase object to a string :param element: An ElementBase object :return: A full description of its content :raise TypeError: Invalid object """ # Check type try: assert isinstance(element, sleekxmpp.ElementBase) except AssertionError: raise TypeError("N...
def create_room(self, room, service, nick, config=None, callback=None, errback=None, room_jid=None): """ Prepares the creation of a room. The callback is a method with two arguments: - room: Bare JID of the room - nick: Nick used to create the room The errback is a method with 4 arguments: - room: Bare JID of the room ...
JID if not given room_jid = sleekxmpp.JID(local=room, domain=service).bare self.__logger.debug("... Room JID: %s", room_jid) if not self.__rooms: # First room to create: register to events self.__xmpp.add_event_handler("presence", self.__on_presence) # Store information self.__rooms[room_jid] = RoomData(room_jid, nick,...
def __safe_callback(self, room_data): """ Safe use of the callback method, to avoid errors propagation :param room_data: A RoomData object """ method = room_data.callback if method is not None: try: method(room_data.room, room_data.nick) except Exception as ex: self.__logger.exception("Error calling back room creator: ...
def __safe_errback(self, room_data, err_condition, err_text): """ Safe use of the callback method, to avoid errors propagation :param room_data: A RoomData object :param err_condition: Category of error :param err_text: Description of the error """ method = room_data.errback if method is not None: try: method(room_data...
def __on_presence(self, data): """ Got a presence stanza """ room_jid = data['from'].bare muc_presence = data['muc'] room = muc_presence['room'] nick = muc_presence['nick'] with self.__lock: try: # Get room state machine room_data = self.__rooms[room] if room_data.nick != nick: # Not about the room creator return excep...
we own the room # Setup room configuration try: config = self.__muc.getRoomConfig(room_jid) except ValueError: # Can't differentiate IQ errors from a "no configuration" # result: consider it OK self.__logger.warning("Can't get the configuration form for " "XMPP room %s", room_jid) self.__safe_callback(room_data) else: ...
def __call(self): """ Calls the callback method """ try: if self.__callback is not None: self.__callback(self.__successes, self.__errors) except Exception as ex: self.__logger.exception("Error calling back count down " "handler: %s", ex) else: self.__called = True
def __mark(self, element, mark_set): """ Marks an element :param element: The element to mark :param mark_set: The set corresponding to the mark :return: True if the element was known """ try: # The given element can be of a different type than the original # one (JID instead of str, ...), so we retrieve the original o...
def do_refresh(self,args): """Refresh the view of the eni""" pprint(AwsConnectionFactory.getEc2Client().describe_network_interfaces(NetworkInterfaceIds=[self.physicalId]));
def do_super(parser, token): ''' Access the parent templates block. {% super name %} ''' name = token.strip() return ast.YieldFrom( value=_a.Call(_a.Attribute(_a.Call(_a.Name('super')), name), [ # _a.Attribute(_a.Name('context'), 'parent'), _a.Name('context'), ]) )
def _create_with_scope(body, kwargs): ''' Helper function to wrap a block in a scope stack: with ContextScope(context, **kwargs) as context: ... body ... ''' return ast.With( items=[ ast.withitem( context_expr=_a.Call( _a.Name('ContextScope'), [_a.Name('context')], keywords=kwargs, ), optional_vars=_a.Name('context', c...
def do_for(parser, token): ''' {% for a, b, c in iterable %} {% endfor %} We create the structure: with ContextWrapper(context) as context: for a, b, c in iterable: context.update(a=a, b=b, c=c) ... If there is a {% empty %} clause, we create: if iterable: { above code } else: { empty clause } ''' code = ast.parse('for...
at the start of the loop body body.insert(0, ast.Expr(value=_a.Call( _a.Attribute(_a.Name('context'), 'update'), keywords=kwargs ))) loop.body = body node = _create_with_scope([loop], []) if end == 'empty': # Now we wrap our for block in: # if loop.iter: # else: empty, _ = parser.parse_nodes_until('endfor') node = ast....
def macro(parser, token): ''' Works just like block, but does not render. ''' name = token.strip() parser.build_method(name, endnodes=['endmacro']) return ast.Yield(value=ast.Str(s=''))
def use(parser, token): ''' Counterpart to `macro`, lets you render any block/macro in place. ''' args, kwargs = parser.parse_args(token) assert isinstance(args[0], ast.Str), \ 'First argument to "include" tag must be a string' name = args[0].s action = ast.YieldFrom( value=_a.Call(_a.Attribute(_a.Name('self'), name), ...
def execute(self, method, args, kwargs): """ Execute the given method and stores its result. The result is considered "done" even if the method raises an exception :param method: The method to execute :param args: Method positional arguments :param kwargs: Method keyword arguments :raise Exception: The exception raised...
def result(self, timeout=None): """ Waits up to timeout for the result the threaded job. Returns immediately the result if the job has already been done. :param timeout: The maximum time to wait for a result (in seconds) :raise OSError: The timeout raised before the job finished :raise Exception: Raises the exception t...
def get_link(self, peer): """ Retrieves a link to the peer :param peer: A Peer description :return: A link to the peer, None if none available """ assert isinstance(peer, Peer) for protocol in self._protocols: try: # Try to get a link return protocol.get_link(peer) except ValueError: # Peer can't be handled by this pro...
def send(self, message): """ Sends a message (synchronous) :param message: Message to send :return: Message response(s) """ future = self.post(message) future.join() return future.result
def resolve_composed_functions(data, recursive=True): """ Calls `ComposedFunction`s and returns its return value. By default, this function will recursively iterate dicts, lists, tuples, and sets and replace all `ComposedFunction`s with their return value. """ if isinstance(data, ComposedFunction): data = data() if rec...
def write(self, metadata, payload): """Write metadata metadata is string:string dict. payload must be encoded as string. """ a = self.get_active_archive() a.write(metadata, payload) if self._should_roll_archive(): self._roll_archive()
async def main(): """ Main code (synchronous requests) """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos by dedicated method (with json schema validation) print("\nCall bma.node.summary:") response = await client(bma.node.summary) print(response) # Ge...
summary infos (direct REST GET request) print("\nCall direct get on node/summary") response = await client.get('node/summary', rtype=RESPONSE_AIOHTTP, schema=summary_schema) print(response) # Close client aiohttp session await client.close()
def might_prefer(self, **items): '''Items to take precedence if their values are not None (never saved)''' self._overrides = dict((k, v) for (k, v) in items.items() if v is not None)
def sync_with(self, config, conflict_resolver): '''Synchronizes current set of key/values in this instance with those in the config.''' if not config.has_section(self._name): config.add_section(self._name) resolved = self._sync_and_resolve(config, conflict_resolver) self._add_new_items(config, resolved)
def _sync_and_resolve(self, config, resolver): '''Synchronize all items represented by the config according to the resolver and return a set of keys that have been resolved.''' resolved = set() for key, theirs in config.items(self._name): theirs = self._real_value_of(theirs) if key in self: mine = self[key] value = res...
def _add_new_items(self, config, seen): '''Add new (unseen) items to the config.''' for (key, value) in self.items(): if key not in seen: self._set_value(config, key, value)
def upload(self, baseurl, filename): """Upload filename to this work""" # Prof is really dirty, we need to re-get the project page before upload payload = { 'id_projet': self.field } prof_session.post(baseurl+"/main.php", params=payload) # We also need to get the upload page... payload = { 'id': int(self.work_id) } pro...
def get_all_classes(module_name): """Load all non-abstract classes from package""" module = importlib.import_module(module_name) return getmembers(module, lambda m: isclass(m) and not isabstract(m))
def get(self, table_name): """Load table class by name, class not yet initialized""" assert table_name in self.tabs, \ "Table not avaiable. Avaiable tables: {}".format( ", ".join(self.tabs.keys()) ) return self.tabs[table_name]
def _update_sys_path(self, package_path=None): """Updates and adds current directory to sys path""" self.package_path = package_path if not self.package_path in sys.path: sys.path.append(self.package_path)
def find_tabs(self, custom_table_classes=None): """Finds all classes that are subcalss of Table and loads them into a dictionary named tables.""" for module_name in get_all_modules(self.package_path): for name, _type in get_all_classes(module_name): # pylint: disable=W0640 subclasses = [Table] + (custom_table_classes o...
def describe_all(self, full=False): """Prints description information about all tables registered Args: full (bool): Also prints description of post processors. """ for table in self.tabs: yield self.tabs[table]().describe(full)
def _connect(self): """Try to create a connection to the database if not yet connected. """ if self._connection is not None: raise RuntimeError('Close connection first.') self._connection = connect(self._database, **self._kwds) self._connection.isolation_level = None
def add_argparser(self, root, parents): """ Add arguments for this command. """ parser = root.add_parser('diff', parents=parents) parser.set_defaults(func=self) parser.add_argument( '--secrets', dest='secrets', action='store', help='Path to the authorization secrets file (client_secrets.json).' ) parser.add_argument( '...
def diff(self, report_a, report_b): """ Generate a diff for two data reports. """ arguments = GLOBAL_ARGUMENTS + ['run_date'] output = OrderedDict([ ('a', OrderedDict([(arg, report_a[arg]) for arg in arguments])), ('b', OrderedDict([(arg, report_b[arg]) for arg in arguments])), ('queries', []) ]) output['a'] for query_...
else None percent_b = float(b) / total_b if total_b > 0 else None if label == 'total' or data_type == 'TIME' or percent_a is None or percent_b is None: point_change = None else: point_change = percent_b - percent_a diff['data'][metric][label] = OrderedDict([ ('change', change), ('percent_change', percent_change), ('poi...
def txt(self, diff, f): """ Generate a text report for a diff. """ env = Environment( loader=PackageLoader('clan', 'templates'), trim_blocks=True, lstrip_blocks=True ) template = env.get_template('diff.txt') def format_row(label, values): change = format_comma(values['change']) percent_change = '{:.1%}'.format(values['...
def html(self, diff, f): """ Generate a text report for a diff. """ env = Environment(loader=PackageLoader('clan', 'templates')) template = env.get_template('diff.html') def number_class(v): if v is None: return '' if v > 0: return 'positive' elif v < 0: return 'negative' return '' context = { 'diff': diff, 'GLOBAL_ARG...
def render_html(self, request, instance, context): """ Custom rendering function for HTML output """ render_template = self.get_render_template(request, instance, email_format='html') if not render_template: return str(u"{No HTML rendering defined for class '%s'}" % self.__class__.__name__) instance_context = self.get_...
def render_text(self, request, instance, context): """ Custom rendering function for HTML output """ render_template = self.get_render_template(request, instance, email_format='text') if not render_template: # If there is no TEXT variation, create it by removing the HTML tags. base_url = request.build_absolute_uri('/')...
def copy_data(self): """ Copy the data from the it's point of origin, serializing it, storing it serialized as well as in it's raw form and calculate a running hash of the serialized representation """ HASH_FUNCTION = hashlib.sha256() try: raw_iterator = self.get_binary_iterator() except AttributeError: raw_iterator = ...
def get_binary_iterator(self): """ Generator to stream the remote file piece by piece. """ CHUNK_SIZE = 1024 return (item for item in requests.get(self.url).iter_content(CHUNK_SIZE))
def get_binary_iterator(self): """ Generator to read a file piece by piece. """ CHUNK_SIZE = 1024 file_object = open(self.path) while True: data = file_object.read(CHUNK_SIZE) if not data: break yield data file_object.close()
def command_request(self, method, path): """ Returns a callable request for a given http method and API path. You can then use this request to execute the command, and get the response value: >>> rqst = client.command_request('get', '/api/hcl') >>> resp, ok = rqst() Parameters ---------- method : str the http method va...
def path_requests(self, path): """ Returns a Resource instace that will have attributes, one for each of the http-methods supported on that path. For example: >>> hcl_api = client.path_requests('/api/hcl/{id}') >>> dir(hcl_api) [u'delete', u'get', u'put'] >>> resp, ok = hcl_api.get(id='Arista_vEOS') Parameters --------...
def get_add_link(self): """ Appends the popup=1 query string to the url so the destination url treats it as a popup. """ url = super(TaggedRelationWidget, self).get_add_link() if url: qs = self.get_add_qs() if qs: url = "%s&%s" % (url, urllib.urlencode(qs)) return url
def render_view(parser, token): """ Return an string version of a View with as_string method. First argument is the name of the view. Any other arguments should be keyword arguments and will be passed to the view. Example: {% render_view viewname var1=xx var2=yy %} """ bits = token.split_contents() n = len(bits) if n <...
def bundle_view(parser, token): """ Returns an string version of a bundle view. This is done by calling the `get_string_from_view` method of the provided bundle. This tag expects that the request object as well as the the original url_params are available in the context. Requires two arguments bundle and the name of th...
def bundle_url(parser, token): """ Returns an a url for given a bundle and a view name. This is done by calling the `get_view_url` method of the provided bundle. This tag expects that the request object as well as the the original url_params are available in the context. Requires two arguments bundle and the name of th...
TemplateSyntaxError("'%s' takes at least two arguments" " bundle and view_name" % bits[0]) bundle = parser.compile_filter(bits[1]) viewname = parser.compile_filter(bits[2]) kwargs = {} asvar = None bits = bits[2:] if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] if len(bits): for bit in bits: m...
def user_url(user, bundle): """ Filter for a user object. Checks if a user has permission to change other users. """ if not user: return False bundle = bundle.admin_site.get_bundle_for_model(User) edit = None if bundle: edit = bundle.get_view_url('main', user) return edit
def groupby(data, keys=None, size=None, min_size=None, max_size=None, contiguous=False): """ :param data: :param keys: :param size: :param min_size: :param max_size: :param contiguous: MAINTAIN THE ORDER OF THE DATA, STARTING THE NEW GROUP WHEN THE SELECTOR CHANGES :return: return list of (keys, values) PAIRS, WHERE ke...
# CAN RETURN Null, WHICH DOES NOT PLAY WELL WITH __cmp__ def _output(): start = 0 prev = accessor(data[0]) for i, d in enumerate(data): curr = accessor(d) if curr != prev: group = {} for k, gg in zip(keys, prev): group[k] = gg yield Data(group), data[start:i:] start = i prev = curr group = {} for k, gg in zip(keys, pre...
def ranks(self) -> List[str]: """:class:`list` of :class:`str`: Ranks in their hierarchical order.""" return list(OrderedDict.fromkeys((m.rank for m in self.members)))
def from_content(cls, content): """Creates an instance of the class from the HTML content of the guild's page. Parameters ----------- content: :class:`str` The HTML content of the page. Returns ---------- :class:`Guild` The guild contained in the page or None if it doesn't exist. Raises ------ InvalidContent If content...
def from_tibiadata(cls, content): """Builds a guild object from a TibiaData character response. Parameters ---------- content: :class:`str` The json string from the TibiaData response. Returns ------- :class:`Guild` The guild contained in the description or ``None``. Raises ------ InvalidContent If content is not a JSO...
member["nick"] or None, member["level"], member["vocation"], joined=parse_tibiadata_date(member["joined"]), online=member["status"] == "online")) for invited in guild_obj["invited"]: guild.invites.append(GuildInvite(invited["name"], parse_tibiadata_date(invited["invited"]))) if isinstance(guild_data["guildhall"], dict)...
def _parse_current_member(self, previous_rank, values): """ Parses the column texts of a member row into a member dictionary. Parameters ---------- previous_rank: :class:`dict`[int, str] The last rank present in the rows. values: tuple[:class:`str`] A list of row contents. """ rank, name, vocation, level, joined, statu...
def _parse_application_info(self, info_container): """ Parses the guild's application info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = applications_regex.search(info_container.text) if m: self.open_applications = m.group(1) == "opened"
def _parse_guild_disband_info(self, info_container): """ Parses the guild's disband info, if available. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = disband_regex.search(info_container.text) if m: self.disband_condition = m.group(2) self.disband_date = ...
def _parse_guild_guildhall(self, info_container): """ Parses the guild's guildhall info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = guildhall_regex.search(info_container.text) if m: paid_until = parse_tibia_date(m.group("date").replace("\xa0", " ")) s...
def _parse_guild_homepage(self, info_container): """ Parses the guild's homepage info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = homepage_regex.search(info_container.text) if m: self.homepage = m.group(1)
def _parse_guild_info(self, info_container): """ Parses the guild's general information and applies the found values. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = founded_regex.search(info_container.text) if m: description = m.group("desc").strip() self...
def _parse_logo(self, parsed_content): """ Parses the guild logo and saves it to the instance. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the page. Returns ------- :class:`bool` Whether the logo was found or not. """ logo_img = parsed_content.find('img', {'height': '64'}) if logo_img i...
def _parse_guild_members(self, parsed_content): """ Parses the guild's member and invited list. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the guild's page """ member_rows = parsed_content.find_all("tr", {'bgcolor': ["#D4C0A1", "#F1E0C6"]}) previous_rank = {} for row in member_rows: co...
def _parse_invited_member(self, values): """ Parses the column texts of an invited row into a invited dictionary. Parameters ---------- values: tuple[:class:`str`] A list of row contents. """ name, date = values if date != "Invitation Date": self.invites.append(GuildInvite(name, date))
def get_world_list_url(cls, world): """Gets the Tibia.com URL for the guild section of a specific world. Parameters ---------- world: :class:`str` The name of the world. Returns ------- :class:`str` The URL to the guild's page """ return GUILD_LIST_URL + urllib.parse.quote(world.title().encode('iso-8859-1'))
def get_world_list_url_tibiadata(cls, world): """Gets the TibiaData.com URL for the guild list of a specific world. Parameters ---------- world: :class:`str` The name of the world. Returns ------- :class:`str` The URL to the guild's page. """ return GUILD_LIST_URL_TIBIADATA % urllib.parse.quote(world.title().encode('is...
def list_from_content(cls, content): """ Gets a list of guilds from the HTML content of the world guilds' page. Parameters ---------- content: :class:`str` The HTML content of the page. Returns ------- :class:`list` of :class:`ListedGuild` List of guilds in the current world. ``None`` if it's the list of a world that d...
in header.text header, *rows = container.find_all("tr", {'bgcolor': ["#D4C0A1", "#F1E0C6"]}) for row in rows: columns = row.find_all('td') logo_img = columns[0].find('img')["src"] description_lines = columns[1].get_text("\n").split("\n", 1) name = description_lines[0] description = None if len(description_lines) > 1: d...
def list_from_tibiadata(cls, content): """Builds a character object from a TibiaData character response. Parameters ---------- content: :class:`str` A string containing the JSON response from TibiaData. Returns ------- :class:`list` of :class:`ListedGuild` The list of guilds contained. Raises ------ InvalidContent If c...
def merge_text_nodes_on(self, node): """Merges all consecutive non-translatable text nodes into one""" if not isinstance(node, ContainerNode) or not node.children: return new_children = [] text_run = [] for i in node.children: if isinstance(i, Text) and not i.translatable: text_run.append(i.escaped()) else: if text_run...
def push_state(self): """ Push a copy of the topmost state on top of the state stack, returns the new top. """ new = dict(self.states[-1]) self.states.append(new) return self.state
def enter_node(self, ir_node): """ Enter the given element; keeps track of `cdata`; subclasses may extend by overriding """ this_is_cdata = (isinstance(ir_node, Element) and ir_node.name in self.cdata_elements) self.state['is_cdata'] = bool(self.state.get('is_cdata')) or this_is_cdata
def watch(static_root, watch_paths=None, on_reload=None, host='localhost', port=5555, server_base_path="/", watcher_interval=1.0, recursive=True, open_browser=True, open_browser_delay=1.0): """Initialises an HttpWatcherServer to watch the given path for changes. Watches until the IO loop is terminated, or a keyboard in...
watcher server. recursive: Whether to monitor the watch path recursively. open_browser: Whether or not to automatically attempt to open the user's browser at the root URL of the project (default: True). open_browser_delay: The number of seconds to wait before attempting to open the user's browser. """ server = httpwatc...
def query(self): """Parse query string using given grammar. :returns: AST that represents the query in the given grammar. """ tree = pypeg2.parse(self._query, parser(), whitespace="") for walker in query_walkers(): tree = tree.accept(walker) return tree
def normalise_key(self, key): """Make sure key is a valid python attribute""" key = key.replace('-', '_') if key.startswith("noy_"): key = key[4:] return key
def find_value(self, key): """Find a value and return it""" values = self.values if key not in values: raise AttributeError("Config has no value for {}".format(key)) val = values[key] if isinstance(val, Default): return val.val else: return val
def use_options(self, options, extractor=None): """ If extractor isn't specified, then just update self.values with options. Otherwise update values with whatever the result of calling extractor with our template and these options returns Also make sure all keys are transformed into valid python attribute names """ # E...
def find_config_file(self): """ Find where our config file is if there is any If the value for the config file is a default and it doesn't exist then it is silently ignored. If however, the value isn't a default and it doesn't exist, an error is raised """ filename = self.values.get('config_file', Default('noy.json')) ...
def apply_config_file(self, filename): """ Add options from config file to self.values Leave alone existing values that are not an instance of Default """ def extractor(template, options): """Ignore things that are existing non default values""" for name, val in options: normalised = self.normalise_key(name) if normali...
def use_config_file(self): """Find and apply the config file""" self.config_file = self.find_config_file() if self.config_file: self.apply_config_file(self.config_file)
def setup(self, options=None, extractor=None): """ Put options onto the config and put anything from a config file onto the config. If extractor is specified, it is used to extract values from the options dictionary """ # Get our programmatic options self._util.use_options(options, extractor) # Overwrite non defaults i...
def recursive_asdict(d): """Convert Suds object into serializable format.""" out = {} for k, v in asdict(d).iteritems(): if hasattr(v, '__keylist__'): out[k] = recursive_asdict(v) elif isinstance(v, list): out[k] = [] for item in v: if hasattr(item, '__keylist__'): out[k].append(recursive_asdict(item)) else: out[k].app...
def index(): """Query Elasticsearch using "collection" param in query string.""" collection_names = request.values.getlist('collection') # Validation of collection names. collections = Collection.query if collection_names: collections = collections.filter( Collection.name.in_(collection_names)) assert len(collection_na...
def from_content(cls, content): """Parses a Tibia.com response into a :class:`World`. Parameters ---------- content: :class:`str` The raw HTML from the server's information page. Returns ------- :class:`World` The World described in the page, or ``None``. Raises ------ InvalidContent If the provided content is not the ...
world
def from_tibiadata(cls, content): """Parses a TibiaData.com response into a :class:`World` Parameters ---------- content: :class:`str` The raw JSON content from TibiaData Returns ------- :class:`World` The World described in the page, or ``None``. Raises ------ InvalidContent If the provided content is not a TibiaData ...
world except KeyError: raise InvalidContent("content is not a world json response from TibiaData")
def _parse_world_info(self, world_info_table): """ Parses the World Information table from Tibia.com and adds the found values to the object. Parameters ---------- world_info_table: :class:`list`[:class:`bs4.Tag`] """ world_info = {} for row in world_info_table: cols_raw = row.find_all('td') cols = [ele.text.strip() fo...
> 90: year += 1900 else: year += 2000 self.creation_date = "%d-%02d" % (year, month) for k, v in world_info.items(): try: setattr(self, k, v) except AttributeError: pass
def _parse_battleye_status(self, battleye_string): """Parses the BattlEye string and applies the results. Parameters ---------- battleye_string: :class:`str` String containing the world's Battleye Status. """ m = battleye_regexp.search(battleye_string) if m: self.battleye_protected = True self.battleye_date = parse_tib...
def _parse_tables(cls, parsed_content): """ Parses the information tables found in a world's information page. Parameters ---------- parsed_content: :class:`bs4.BeautifulSoup` A :class:`BeautifulSoup` object containing all the content. Returns ------- :class:`OrderedDict`[:class:`str`, :class:`list`[:class:`bs4.Tag`]] ...
def from_content(cls, content): """Parses the content of the World Overview section from Tibia.com into an object of this class. Parameters ---------- content: :class:`str` The HTML content of the World Overview page in Tibia.com Returns ------- :class:`WorldOverview` An instance of this class containing all the inform...
def from_tibiadata(cls, content): """Parses the content of the World Overview section from TibiaData.com into an object of this class. Notes ----- Due to TibiaData limitations, :py:attr:`record_count` and :py:attr:`record_date` are unavailable object. Additionally, the listed worlds in :py:attr:`worlds` lack some infor...
world.online_count = world_json["online"] world_overview.worlds.append(world) return world_overview except KeyError: raise InvalidContent("content is not a worlds json response from TibiaData.com.")
def _parse_worlds(self, world_rows): """Parses the world columns and adds the results to :py:attr:`worlds`. Parameters ---------- world_rows: :class:`list` of :class:`bs4.Tag` A list containing the rows of each world. """ for world_row in world_rows: cols = world_row.find_all("td") name = cols[0].text.strip() status = ...