Search is not available for this dataset
text
stringlengths
75
104k
def breadcrumbs(self, tree_alias, context): """Builds and returns breadcrumb trail structure for 'sitetree_breadcrumbs' tag. :param str|unicode tree_alias: :param Context context: :rtype: list|str """ tree_alias, sitetree_items = self.init_tree(tree_alias, context) ...
def tree(self, tree_alias, context): """Builds and returns tree structure for 'sitetree_tree' tag. :param str|unicode tree_alias: :param Context context: :rtype: list|str """ tree_alias, sitetree_items = self.init_tree(tree_alias, context) if not sitetree_items:...
def children(self, parent_item, navigation_type, use_template, context): """Builds and returns site tree item children structure for 'sitetree_children' tag. :param TreeItemBase parent_item: :param str|unicode navigation_type: menu, sitetree :param str|unicode use_template: :par...
def get_children(self, tree_alias, item): """Returns item's children. :param str|unicode tree_alias: :param TreeItemBase|None item: :rtype: list """ if not self.current_app_is_admin(): # We do not need i18n for a tree rendered in Admin dropdown. t...
def update_has_children(self, tree_alias, tree_items, navigation_type): """Updates 'has_children' attribute for tree items inplace. :param str|unicode tree_alias: :param list tree_items: :param str|unicode navigation_type: sitetree, breadcrumbs, menu """ get_children = s...
def filter_items(self, items, navigation_type=None): """Filters sitetree item's children if hidden and by navigation type. NB: We do not apply any filters to sitetree in admin app. :param list items: :param str|unicode navigation_type: sitetree, breadcrumbs, menu :rtype: list ...
def get_ancestor_item(self, tree_alias, base_item): """Climbs up the site tree to resolve root item for chosen one. :param str|unicode tree_alias: :param TreeItemBase base_item: :rtype: TreeItemBase """ parent = None if hasattr(base_item, 'parent') and base_item...
def tree_climber(self, tree_alias, base_item): """Climbs up the site tree to mark items of current branch. :param str|unicode tree_alias: :param TreeItemBase base_item: """ if base_item is not None: base_item.in_current_branch = True if hasattr(base_item,...
def resolve_var(self, varname, context=None): """Resolves name as a variable in a given context. If no context specified page context' is considered as context. :param str|unicode varname: :param Context context: :return: """ context = context or self.current_pa...
def sitetree_tree(parser, token): """Parses sitetree tag parameters. Two notation types are possible: 1. Two arguments: {% sitetree_tree from "mytree" %} Used to render tree for "mytree" site tree. 2. Four arguments: {% sitetree_tree from "mytree" template "sit...
def sitetree_children(parser, token): """Parses sitetree_children tag parameters. Six arguments: {% sitetree_children of someitem for menu template "sitetree/mychildren.html" %} Used to render child items of specific site tree 'someitem' using template "sitetree/mychildren.h...
def sitetree_breadcrumbs(parser, token): """Parses sitetree_breadcrumbs tag parameters. Two notation types are possible: 1. Two arguments: {% sitetree_breadcrumbs from "mytree" %} Used to render breadcrumb path for "mytree" site tree. 2. Four arguments: {% site...
def sitetree_menu(parser, token): """Parses sitetree_menu tag parameters. {% sitetree_menu from "mytree" include "trunk,1,level3" %} Used to render trunk, branch with id 1 and branch aliased 'level3' elements from "mytree" site tree as a menu. These are reserved aliases: ...
def render(context, tree_items, use_template): """Render helper is used by template node functions to render given template with given tree items in context. """ context.push() context['sitetree_items'] = tree_items if isinstance(use_template, FilterExpression): use_template = use_temp...
def for_tag(cls, parser, token, preposition, error_hint): """Node constructor to be used in tags.""" tokens = token.split_contents() if len(tokens) >= 3 and tokens[1] == preposition: as_var = cls.get_as_var(tokens) tree_alias = parser.compile_filter(tokens[2]) ...
def get_model_url_name(model_nfo, page, with_namespace=False): """Returns a URL for a given Tree admin page type.""" prefix = '' if with_namespace: prefix = 'admin:' return ('%s%s_%s' % (prefix, '%s_%s' % model_nfo, page)).lower()
def _reregister_tree_admin(): """Forces unregistration of tree admin class with following re-registration.""" try: admin.site.unregister(MODEL_TREE_CLASS) except NotRegistered: pass admin.site.register(MODEL_TREE_CLASS, _TREE_ADMIN())
def redirects_handler(*args, **kwargs): """Fixes Admin contrib redirects compatibility problems introduced in Django 1.4 by url handling changes. """ path = args[0].path shift = '../' if 'delete' in path: # Weird enough 'delete' is not handled by TreeItemAdmin::response_change(). ...
def _redirect(self, request, response): """Generic redirect for item editor.""" if '_addanother' in request.POST: return HttpResponseRedirect('../item_add/') elif '_save' in request.POST: return HttpResponseRedirect('../') elif '_continue' in request.POST: ...
def response_add(self, request, obj, post_url_continue=None, **kwargs): """Redirects to the appropriate items' 'continue' page on item add. As we administer tree items within tree itself, we should make some changes to redirection process. """ if post_url_continue is None: ...
def response_change(self, request, obj, **kwargs): """Redirects to the appropriate items' 'add' page on item change. As we administer tree items within tree itself, we should make some changes to redirection process. """ return self._redirect(request, super(TreeItemAdmin, self)...
def get_form(self, request, obj=None, **kwargs): """Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself. """ if obj is not None and obj.parent is not None: self.previous_parent = obj.parent previous_parent_id = self.previ...
def get_tree(self, request, tree_id, item_id=None): """Fetches Tree for current or given TreeItem.""" if tree_id is None: tree_id = self.get_object(request, item_id).tree_id self.tree = MODEL_TREE_CLASS._default_manager.get(pk=tree_id) self.tree.verbose_name_plural = self.tre...
def item_move(self, request, tree_id, item_id, direction): """Moves item up or down by swapping 'sort_order' field values of neighboring items.""" current_item = MODEL_TREE_ITEM_CLASS._default_manager.get(pk=item_id) if direction == 'up': sort_order = 'sort_order' else: ...
def save_model(self, request, obj, form, change): """Saves TreeItem model under certain Tree. Handles item's parent assignment exception. """ if change: # No, you're not allowed to make item parent of itself if obj.parent is not None and obj.parent.id == obj.id: ...
def get_urls(self): """Manages not only TreeAdmin URLs but also TreeItemAdmin URLs.""" urls = super(TreeAdmin, self).get_urls() prefix_change = 'change/' if DJANGO_POST_19 else '' sitetree_urls = [ url(r'^change/$', redirects_handler, name=get_tree_item_url_name('changelist...
def dump_view(cls, request): """Dumps sitetrees with items using django-smuggler. :param request: :return: """ from smuggler.views import dump_to_response return dump_to_response(request, [MODEL_TREE, MODEL_TREE_ITEM], filename_prefix='sitetrees')
def tree(alias, title='', items=None, **kwargs): """Dynamically creates and returns a sitetree. :param str|unicode alias: :param str|unicode title: :param iterable items: dynamic sitetree items objects created by `item` function. :param kwargs: Additional arguments to pass to tree item initializer....
def item( title, url, children=None, url_as_pattern=True, hint='', alias='', description='', in_menu=True, in_breadcrumbs=True, in_sitetree=True, access_loggedin=False, access_guest=False, access_by_perms=None, perms_mode_all=True, **kwargs): """Dynamically creates and returns a sitetree item object...
def import_app_sitetree_module(app): """Imports sitetree module from a given app. :param str|unicode app: Application name :return: module|None """ module_name = settings.APP_MODULE_NAME module = import_module(app) try: sub_module = import_module('%s.%s' % (app, module_name)) ...
def import_project_sitetree_modules(): """Imports sitetrees modules from packages (apps). Returns a list of submodules. :rtype: list """ from django.conf import settings as django_settings submodules = [] for app in django_settings.INSTALLED_APPS: module = import_app_sitetree_module...
def get_app_n_model(settings_entry_name): """Returns tuple with application and tree[item] model class names. :param str|unicode settings_entry_name: :rtype: tuple """ try: app_name, model_name = getattr(settings, settings_entry_name).split('.') except ValueError: raise Improper...
def get_model_class(settings_entry_name): """Returns a certain sitetree model as defined in the project settings. :param str|unicode settings_entry_name: :rtype: TreeItemBase|TreeBase """ app_name, model_name = get_app_n_model(settings_entry_name) try: model = apps_get_model(app_name, ...
async def asgi_send(self, message: dict) -> None: """Called by the ASGI instance to send a message.""" if message["type"] == "http.response.start" and self.state == ASGIHTTPState.REQUEST: self.response = message elif message["type"] == "http.response.body" and self.state in { ...
async def asgi_send(self, message: dict) -> None: """Called by the ASGI instance to send a message.""" if message["type"] == "websocket.accept" and self.state == ASGIWebsocketState.HANDSHAKE: headers = build_and_validate_headers(message.get("headers", [])) raise_if_subprotocol_pr...
async def serve(app: ASGIFramework, config: Config) -> None: """Serve an ASGI framework app given the config. This allows for a programmatic way to serve an ASGI framework, it can be used via, .. code-block:: python asyncio.run(serve(app, config)) It is assumed that the event-loop is con...
async def serve( app: ASGIFramework, config: Config, *, task_status: trio._core._run._TaskStatus = trio.TASK_STATUS_IGNORED, ) -> None: """Serve an ASGI framework app given the config. This allows for a programmatic way to serve an ASGI framework, it can be used via, .. code-block:: py...
def from_mapping( cls: Type["Config"], mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any ) -> "Config": """Create a configuration from a mapping. This allows either a mapping to be directly passed or as keyword arguments, for example, .. code-block:: python ...
def from_pyfile(cls: Type["Config"], filename: FilePath) -> "Config": """Create a configuration from a Python file. .. code-block:: python Config.from_pyfile('hypercorn_config.py') Arguments: filename: The filename which gives the path to the file. """ ...
def from_toml(cls: Type["Config"], filename: FilePath) -> "Config": """Load the configuration values from a TOML formatted file. This allows configuration to be loaded as so .. code-block:: python Config.from_toml('config.toml') Arguments: filename: The filena...
def from_object(cls: Type["Config"], instance: Union[object, str]) -> "Config": """Create a configuration from a Python object. This can be used to reference modules or objects within modules for example, .. code-block:: python Config.from_object('module') Conf...
def emit_spans(self): """Main function to log all the annotations stored during the entire request. This is done if the request is sampled and the response was a success. It also logs the service (`ss` and `sr`) or the client ('cs' and 'cr') annotations. """ # FIXME: Sho...
def create_attrs_for_span( sample_rate=100.0, trace_id=None, span_id=None, use_128bit_trace_id=False, ): """Creates a set of zipkin attributes for a span. :param sample_rate: Float between 0.0 and 100.0 to determine sampling rate :type sample_rate: float :param trace_id: Optional 16-cha...
def create_http_headers_for_new_span(context_stack=None, tracer=None): """ Generate the headers for a new zipkin span. .. note:: If the method is not called from within a zipkin_trace context, empty dict will be returned back. :returns: dict containing (X-B3-TraceId, X-B3-SpanId, X-B3...
def _get_current_context(self): """Returns the current ZipkinAttrs and generates new ones if needed. :returns: (report_root_timestamp, zipkin_attrs) :rtype: (bool, ZipkinAttrs) """ # This check is technically not necessary since only root spans will have # sample_rate, z...
def start(self): """Enter the new span context. All annotations logged inside this context will be attributed to this span. All new spans generated inside this context will have this span as their parent. In the unsampled case, this context still generates new span IDs and pushe...
def stop(self, _exc_type=None, _exc_value=None, _exc_traceback=None): """Exit the span context. Zipkin attrs are pushed onto the threadlocal stack regardless of sampling, so they always need to be popped off. The actual logging of spans depends on sampling and that the logging was correc...
def update_binary_annotations(self, extra_annotations): """Updates the binary annotations for the current span.""" if not self.logging_context: # This is not the root span, so binary annotations will be added # to the log handler when this span context exits. self.bin...
def add_sa_binary_annotation( self, port=0, service_name='unknown', host='127.0.0.1', ): """Adds a 'sa' binary annotation to the current span. 'sa' binary annotations are useful for situations where you need to log where a request is going but the destination...
def override_span_name(self, name): """Overrides the current span name. This is useful if you don't know the span name yet when you create the zipkin_span object. i.e. pyramid_zipkin doesn't know which route the request matched until the function wrapped by the context manager c...
def create_endpoint(port=None, service_name=None, host=None, use_defaults=True): """Creates a new Endpoint object. :param port: TCP/UDP port. Defaults to 0. :type port: int :param service_name: service name as a str. Defaults to 'unknown'. :type service_name: str :param host: ipv4 or ipv6 addre...
def copy_endpoint_with_new_service_name(endpoint, new_service_name): """Creates a copy of a given endpoint with a new service name. :param endpoint: existing Endpoint object :type endpoint: Endpoint :param new_service_name: new service name :type new_service_name: str :returns: zipkin new Endpo...
def build_v1_span(self): """Builds and returns a V1 Span. :return: newly generated _V1Span :rtype: _V1Span """ # We are simulating a full two-part span locally, so set cs=sr and ss=cr full_annotations = OrderedDict([ ('cs', self.timestamp), ('sr',...
def encode_pb_list(pb_spans): """Encode list of protobuf Spans to binary. :param pb_spans: list of protobuf Spans. :type pb_spans: list of zipkin_pb2.Span :return: encoded list. :rtype: bytes """ pb_list = zipkin_pb2.ListOfSpans() pb_list.spans.extend(pb_spans) return pb_list.Serial...
def create_protobuf_span(span): """Converts a py_zipkin Span in a protobuf Span. :param span: py_zipkin Span to convert. :type span: py_zipkin.encoding.Span :return: protobuf's Span :rtype: zipkin_pb2.Span """ # Protobuf's composite types (i.e. Span's local_endpoint) are immutable. # S...
def _hex_to_bytes(hex_id): """Encodes to hexadecimal ids to big-endian binary. :param hex_id: hexadecimal id to encode. :type hex_id: str :return: binary representation. :type: bytes """ if len(hex_id) <= 16: int_id = unsigned_hex_to_signed_int(hex_id) return struct.pack('>q...
def _get_protobuf_kind(kind): """Converts py_zipkin's Kind to Protobuf's Kind. :param kind: py_zipkin's Kind. :type kind: py_zipkin.Kind :return: correcponding protobuf's kind value. :rtype: zipkin_pb2.Span.Kind """ if kind == Kind.CLIENT: return zipkin_pb2.Span.CLIENT elif kind...
def _convert_endpoint(endpoint): """Converts py_zipkin's Endpoint to Protobuf's Endpoint. :param endpoint: py_zipkins' endpoint to convert. :type endpoint: py_zipkin.encoding.Endpoint :return: corresponding protobuf's endpoint. :rtype: zipkin_pb2.Endpoint """ pb_endpoint = zipkin_pb2.Endpoi...
def _convert_annotations(annotations): """Converts py_zipkin's annotations dict to protobuf. :param annotations: annotations dict. :type annotations: dict :return: corresponding protobuf's list of annotations. :rtype: list """ pb_annotations = [] for value, ts in annotations.items(): ...
def create_annotation(timestamp, value, host): """ Create a zipkin annotation object :param timestamp: timestamp of when the annotation occured in microseconds :param value: name of the annotation, such as 'sr' :param host: zipkin endpoint object :returns: zipkin annotation object """ ...
def create_binary_annotation(key, value, annotation_type, host): """ Create a zipkin binary annotation object :param key: name of the annotation, such as 'http.uri' :param value: value of the annotation, such as a URI :param annotation_type: type of annotation, such as AnnotationType.I32 :param...
def create_endpoint(port=0, service_name='unknown', ipv4=None, ipv6=None): """Create a zipkin Endpoint object. An Endpoint object holds information about the network context of a span. :param port: int value of the port. Defaults to 0 :param service_name: service name as a str. Defaults to 'unknown' ...
def copy_endpoint_with_new_service_name(endpoint, service_name): """Copies a copy of a given endpoint with a new service name. This should be very fast, on the order of several microseconds. :param endpoint: existing zipkin_core.Endpoint object :param service_name: str of new service name :returns:...
def annotation_list_builder(annotations, host): """ Reformat annotations dict to return list of corresponding zipkin_core objects. :param annotations: dict containing key as annotation name, value being timestamp in seconds(float). :type host: :class:`zipkin_core.Endpoint` :...
def binary_annotation_list_builder(binary_annotations, host): """ Reformat binary annotations dict to return list of zipkin_core objects. The value of the binary annotations MUST be in string format. :param binary_annotations: dict with key, value being the name and value ...
def create_span( span_id, parent_span_id, trace_id, span_name, annotations, binary_annotations, timestamp_s, duration_s, ): """Takes a bunch of span attributes and returns a thriftpy2 representation of the span. Timestamps passed in are in seconds, they're converted to micros...
def span_to_bytes(thrift_span): """ Returns a TBinaryProtocol encoded Thrift span. :param thrift_span: thrift object to encode. :returns: thrift object in TBinaryProtocol format bytes. """ transport = TMemoryBuffer() protocol = TBinaryProtocol(transport) thrift_span.write(protocol) ...
def encode_bytes_list(binary_thrift_obj_list): # pragma: no cover """ Returns a TBinaryProtocol encoded list of Thrift objects. :param binary_thrift_obj_list: list of TBinaryProtocol objects to encode. :returns: bynary object representing the encoded list. """ transport = TMemoryBuffer() w...
def detect_span_version_and_encoding(message): """Returns the span type and encoding for the message provided. The logic in this function is a Python port of https://github.com/openzipkin/zipkin/blob/master/zipkin/src/main/java/zipkin/internal/DetectingSpanDecoder.java :param message: span to perform ...
def convert_spans(spans, output_encoding, input_encoding=None): """Converts encoded spans to a different encoding. param spans: encoded input spans. type spans: byte array param output_encoding: desired output encoding. type output_encoding: Encoding param input_encoding: optional input encodin...
def push_zipkin_attrs(zipkin_attr): """Stores the zipkin attributes to thread local. .. deprecated:: Use the Tracer interface which offers better multi-threading support. push_zipkin_attrs will be removed in version 1.0. :param zipkin_attr: tuple containing zipkin related attrs :type zip...
def generate_random_128bit_string(): """Returns a 128 bit UTF-8 encoded string. Follows the same conventions as generate_random_64bit_string(). The upper 32 bits are the current time in epoch seconds, and the lower 96 bits are random. This allows for AWS X-Ray `interop <https://github.com/openzipki...
def get_encoder(encoding): """Creates encoder object for the given encoding. :param encoding: desired output encoding protocol. :type encoding: Encoding :return: corresponding IEncoder object :rtype: IEncoder """ if encoding == Encoding.V1_THRIFT: return _V1ThriftEncoder() if en...
def fits(self, current_count, current_size, max_size, new_span): """Checks if the new span fits in the max payload size. Thrift lists have a fixed-size header and no delimiters between elements so it's easy to compute the list size. """ return thrift.LIST_HEADER_SIZE + current_s...
def encode_span(self, v2_span): """Encodes the current span to thrift.""" span = v2_span.build_v1_span() thrift_endpoint = thrift.create_endpoint( span.endpoint.port, span.endpoint.service_name, span.endpoint.ipv4, span.endpoint.ipv6, ) ...
def _create_json_endpoint(self, endpoint, is_v1): """Converts an Endpoint to a JSON endpoint dict. :param endpoint: endpoint object to convert. :type endpoint: Endpoint :param is_v1: whether we're serializing a v1 span. This is needed since in v1 some fields default to an em...
def encode_span(self, v2_span): """Encodes a single span to JSON.""" span = v2_span.build_v1_span() json_span = { 'traceId': span.trace_id, 'name': span.name, 'id': span.id, 'annotations': [], 'binaryAnnotations': [], } ...
def encode_span(self, span): """Encodes a single span to JSON.""" json_span = { 'traceId': span.trace_id, 'id': span.span_id, } if span.name: json_span['name'] = span.name if span.parent_id: json_span['parentId'] = span.parent_id ...
def fits(self, current_count, current_size, max_size, new_span): """Checks if the new span fits in the max payload size.""" return current_size + len(new_span) <= max_size
def encode_span(self, span): """Encodes a single span to protobuf.""" if not protobuf.installed(): raise ZipkinError( 'protobuf encoding requires installing the protobuf\'s extra ' 'requirements. Use py-zipkin[protobuf] in your requirements.txt.' )...
def get_decoder(encoding): """Creates encoder object for the given encoding. :param encoding: desired output encoding protocol :type encoding: Encoding :return: corresponding IEncoder object :rtype: IEncoder """ if encoding == Encoding.V1_THRIFT: return _V1ThriftDecoder() if enc...
def decode_spans(self, spans): """Decodes an encoded list of spans. :param spans: encoded list of spans :type spans: bytes :return: list of spans :rtype: list of Span """ decoded_spans = [] transport = TMemoryBuffer(spans) if six.byte2int(spans) ...
def _convert_from_thrift_endpoint(self, thrift_endpoint): """Accepts a thrift decoded endpoint and converts it to an Endpoint. :param thrift_endpoint: thrift encoded endpoint :type thrift_endpoint: thrift endpoint :returns: decoded endpoint :rtype: Encoding """ i...
def _decode_thrift_annotations(self, thrift_annotations): """Accepts a thrift annotation and converts it to a v1 annotation. :param thrift_annotations: list of thrift annotations. :type thrift_annotations: list of zipkin_core.Span.Annotation :returns: (annotations, local_endpoint, kind)...
def _convert_from_thrift_binary_annotations(self, thrift_binary_annotations): """Accepts a thrift decoded binary annotation and converts it to a v1 binary annotation. """ tags = {} local_endpoint = None remote_endpoint = None for binary_annotation in thrift_binar...
def _decode_thrift_span(self, thrift_span): """Decodes a thrift span. :param thrift_span: thrift span :type thrift_span: thrift Span object :returns: span builder representing this span :rtype: Span """ parent_id = None local_endpoint = None annot...
def _convert_trace_id_to_string(self, trace_id, trace_id_high=None): """ Converts the provided traceId hex value with optional high bits to a string. :param trace_id: the value of the trace ID :type trace_id: int :param trace_id_high: the high bits of the trace ID ...
def _convert_unsigned_long_to_lower_hex(self, value): """ Converts the provided unsigned long value to a hex string. :param value: the value to convert :type value: unsigned long :returns: value as a hex string """ result = bytearray(16) self._write_hex_l...
def _write_hex_long(self, data, pos, value): """ Writes an unsigned long value across a byte array. :param data: the buffer to write the value to :type data: bytearray :param pos: the starting position :type pos: int :param value: the value to write :type...
def date_fixup_pre_processor(transactions, tag, tag_dict, *args): """ Replace illegal February 29, 30 dates with the last day of February. German banks use a variant of the 30/360 interest rate calculation, where each month has always 30 days even February. Python's datetime module won't accept suc...
def mBank_set_transaction_code(transactions, tag, tag_dict, *args): """ mBank Collect uses transaction code 911 to distinguish icoming mass payments transactions, adding transaction_code may be helpful in further processing """ tag_dict['transaction_code'] = int( tag_dict[tag.slug].split...
def mBank_set_iph_id(transactions, tag, tag_dict, *args): """ mBank Collect uses ID IPH to distinguish between virtual accounts, adding iph_id may be helpful in further processing """ matches = iph_id_re.search(tag_dict[tag.slug]) if matches: # pragma no branch tag_dict['iph_id'] = mat...
def mBank_set_tnr(transactions, tag, tag_dict, *args): """ mBank Collect states TNR in transaction details as unique id for transactions, that may be used to identify the same transactions in different statement files eg. partial mt942 and full mt940 Information about tnr uniqueness has been obtaine...
def parse(self, data): '''Parses mt940 data, expects a string with data Args: data (str): The MT940 data Returns: :py:class:`list` of :py:class:`Transaction` ''' # Remove extraneous whitespace and such data = '\n'.join(self.strip(data.split('\n'))) ...
def parse(src, encoding=None): ''' Parses mt940 data and returns transactions object :param src: file handler to read, filename to read or raw data as string :return: Collection of transactions :rtype: Transactions ''' def safe_is_file(filename): try: return os.path.isf...
def join_lines(string, strip=Strip.BOTH): ''' Join strings together and strip whitespace in between if needed ''' lines = [] for line in string.splitlines(): if strip & Strip.RIGHT: line = line.rstrip() if strip & Strip.LEFT: line = line.lstrip() li...
async def json_or_text(response): """Turns response into a properly formatted json or text object""" text = await response.text() if response.headers['Content-Type'] == 'application/json; charset=utf-8': return json.loads(text) return text
async def limited(until): """Handles the message shown when we are ratelimited""" duration = int(round(until - time.time())) mins = duration / 60 fmt = 'We have exhausted a ratelimit quota. Retrying in %.2f seconds (%.3f minutes).' log.warn(fmt, duration, mins)
async def request(self, method, url, **kwargs): """Handles requests to the API""" rate_limiter = RateLimiter(max_calls=59, period=60, callback=limited) # handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so o...
async def get_bot_info(self, bot_id): '''Gets the information of the given Bot ID''' resp = await self.request('GET', '{}/bots/{}'.format(self.BASE, bot_id)) resp['date'] = datetime.strptime(resp['date'], '%Y-%m-%dT%H:%M:%S.%fZ') for k in resp: if resp[k] == '': ...