INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
: param s: a list or set of from id
def per_from_id_in(s, flavors=chat_flavors+inline_flavors): """ :param s: a list or set of from id :param flavors: ``all`` or a list of flavors :return: a seeder function that returns the from id only if the from id is in ``s`` and message flavor is in ``flavors``. ...
: param s: a list or set of from id
def per_from_id_except(s, flavors=chat_flavors+inline_flavors): """ :param s: a list or set of from id :param flavors: ``all`` or a list of flavors :return: a seeder function that returns the from id only if the from id is *not* in ``s`` and message flavor is in ``flavo...
: return: a seeder function that returns an event s source id only if that event s source space equals to event_space.
def per_event_source_id(event_space): """ :return: a seeder function that returns an event's source id only if that event's source space equals to ``event_space``. """ def f(event): if is_event(event): v = peel(event) if v['source']['space'] == event_space...
: param types: all or a list of chat types ( private group channel )
def per_callback_query_chat_id(types='all'): """ :param types: ``all`` or a list of chat types (``private``, ``group``, ``channel``) :return: a seeder function that returns a callback query's originating chat id if the chat type is in ``types``. """ def f(msg): if (f...
: param origins: all or a list of origin types ( chat inline )
def per_callback_query_origin(origins='all'): """ :param origins: ``all`` or a list of origin types (``chat``, ``inline``) :return: a seeder function that returns a callback query's origin identifier if that origin type is in ``origins``. The origin identifier is guaranteed ...
: return: a delegator function that returns a tuple ( func ( seed tuple ) + args kwargs ). That is seed tuple is inserted before supplied positional arguments. By default a thread wrapping func and all those arguments is spawned.
def call(func, *args, **kwargs): """ :return: a delegator function that returns a tuple (``func``, (seed tuple,)+ ``args``, ``kwargs``). That is, seed tuple is inserted before supplied positional arguments. By default, a thread wrapping ``func`` and all those arguments is spawned. ""...
: return: a delegator function that calls the cls constructor whose arguments being a seed tuple followed by supplied * args and ** kwargs then returns the object s run method. By default a thread wrapping that run method is spawned.
def create_run(cls, *args, **kwargs): """ :return: a delegator function that calls the ``cls`` constructor whose arguments being a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns the object's ``run`` method. By default, a thread wrapping that ``run`` method ...
: return: a delegator function that calls the cls constructor whose arguments being a seed tuple followed by supplied * args and ** kwargs then returns a looping function that uses the object s listener to wait for messages and invokes instance method open on_message and on_close accordingly. By default a thread wrappi...
def create_open(cls, *args, **kwargs): """ :return: a delegator function that calls the ``cls`` constructor whose arguments being a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns a looping function that uses the object's ``listener`` to wait for messages ...
Try a list of seeder functions until a condition is met.
def until(condition, fns): """ Try a list of seeder functions until a condition is met. :param condition: a function that takes one argument - a seed - and returns ``True`` or ``False`` :param fns: a list of seeder functions :return: a "composite" seeder function t...
The basic pair producer.
def pair(seeders, delegator_factory, *args, **kwargs): """ The basic pair producer. :return: a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple. :param seeders: If it is a seeder function or a list of one seeder function, it is returned as the final seeder. If it is a list...
: return: a pair producer that ensures the seeder and delegator share the same event space.
def pave_event_space(fn=pair): """ :return: a pair producer that ensures the seeder and delegator share the same event space. """ global _event_space event_space = next(_event_space) @_ensure_seeders_list def p(seeders, delegator_factory, *args, **kwargs): return fn(seeders ...
: return: a pair producer that enables static callback query capturing across seeder and delegator.
def include_callback_query_chat_id(fn=pair, types='all'): """ :return: a pair producer that enables static callback query capturing across seeder and delegator. :param types: ``all`` or a list of chat types (``private``, ``group``, ``channel``) """ @_ensure_seeders_list ...
: return: a pair producer that enables dynamic callback query origin mapping across seeder and delegator.
def intercept_callback_query_origin(fn=pair, origins='all'): """ :return: a pair producer that enables dynamic callback query origin mapping across seeder and delegator. :param origins: ``all`` or a list of origin types (``chat``, ``inline``). Origin mapping is only enabled ...
Access Bot API through a proxy.
def set_proxy(url, basic_auth=None): """ Access Bot API through a proxy. :param url: proxy URL :param basic_auth: 2-tuple ``('username', 'password')`` """ global _pools, _onetime_pool_spec if not url: _pools['default'] = urllib3.PoolManager(**_default_pool_params) _onetime_p...
: type relax: float: param relax: seconds between each: meth:. getUpdates
def run_forever(self, *args, **kwargs): """ :type relax: float :param relax: seconds between each :meth:`.getUpdates` :type offset: int :param offset: initial ``offset`` parameter supplied to :meth:`.getUpdates` :type timeout: int :param timeout: ...
: type maxhold: float: param maxhold: The maximum number of seconds an update is held waiting for a not - yet - arrived smaller update_id. When this number of seconds is up the update is delivered to the message - handling function even if some smaller update_id \ s have not yet arrived. If those smaller update_id \ s ...
def run_forever(self, *args, **kwargs): """ :type maxhold: float :param maxhold: The maximum number of seconds an update is held waiting for a not-yet-arrived smaller ``update_id``. When this number of seconds is up, the update is delivered to the message-hand...
: param data: One of these:
def feed(self, data): """ :param data: One of these: - ``str``, ``unicode`` (Python 2.7), or ``bytes`` (Python 3, decoded using UTF-8) representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object. - a ``dict`` representing...
: return: a dictionary roughly equivalent to { key1: obj. on_key1 key2: obj. on_key2... } but obj does not have to define all methods. It may define the needed ones only.
def make_routing_table(obj, keys, prefix='on_'): """ :return: a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``, but ``obj`` does not have to define all methods. It may define the needed ones only. :param obj: the object :param keys: a list of keys ...
: return: A key function that returns a 2 - tuple ( content_type ( msg [ content_type ] )). In plain English it returns the message s * content type * as the key and the corresponding content as a positional argument to the handler function.
def by_content_type(): """ :return: A key function that returns a 2-tuple (content_type, (msg[content_type],)). In plain English, it returns the message's *content type* as the key, and the corresponding content as a positional argument to the handler function. """ def f(...
: param extractor: a function that takes one argument ( the message ) and returns a portion of message to be interpreted. To extract the text of a chat message use lambda msg: msg [ text ].
def by_command(extractor, prefix=('/',), separator=' ', pass_args=False): """ :param extractor: a function that takes one argument (the message) and returns a portion of message to be interpreted. To extract the text of a chat message, use ``lambda msg: msg['text']``. :param prefix:...
: param prefix: a list of special characters expected to indicate the head of a command.
def by_chat_command(prefix=('/',), separator=' ', pass_args=False): """ :param prefix: a list of special characters expected to indicate the head of a command. :param separator: a command may be followed by arguments separated by ``separator``. :type pass_args: bool :param pass_arg...
: param extractor: a function that takes one argument ( the message ) and returns a portion of message to be interpreted. To extract the text of a chat message use lambda msg: msg [ text ].
def by_regex(extractor, regex, key=1): """ :param extractor: a function that takes one argument (the message) and returns a portion of message to be interpreted. To extract the text of a chat message, use ``lambda msg: msg['text']``. :type regex: str or regex object :param regex...
: param processor: a function to process the key returned by the supplied key function
def process_key(processor, fn): """ :param processor: a function to process the key returned by the supplied key function :param fn: a key function :return: a function that wraps around the supplied key function to further process the key before returning. """ d...
: param fn: a key function
def lower_key(fn): """ :param fn: a key function :return: a function that wraps around the supplied key function to ensure the returned key is in lowercase. """ def lower(key): try: return key.lower() except AttributeError: return key retu...
: param fn: a key function
def upper_key(fn): """ :param fn: a key function :return: a function that wraps around the supplied key function to ensure the returned key is in uppercase. """ def upper(key): try: return key.upper() except AttributeError: return key retu...
: return: a dictionary roughly equivalent to { key1: obj. on_key1 key2: obj. on_key2... } but obj does not have to define all methods. It may define the needed ones only.
def make_routing_table(obj, keys, prefix='on_'): """ :return: a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``, but ``obj`` does not have to define all methods. It may define the needed ones only. :param obj: the object :param keys: a list of keys ...
A class decorator to fill in certain methods and properties to ensure a class can be used by: func:. create_open.
def openable(cls): """ A class decorator to fill in certain methods and properties to ensure a class can be used by :func:`.create_open`. These instance methods and property will be added, if not defined by the class: - ``open(self, initial_msg, seed)`` - ``on_message(self, msg)`` - ``...
Block until a matched message appears.
def wait(self): """ Block until a matched message appears. """ if not self._patterns: raise RuntimeError('Listener has nothing to capture') while 1: msg = self._queue.get(block=True) if any(map(lambda p: filtering.match_all(msg, p), self._pat...
Spawns a thread that calls compute fn ( along with additional arguments * compute_args and ** compute_kwargs ) then applies the returned value to: meth:. Bot. answerInlineQuery to answer the inline query. If a preceding thread is already working for a user that thread is cancelled thus ensuring at most one active threa...
def answer(outerself, inline_query, compute_fn, *compute_args, **compute_kwargs): """ Spawns a thread that calls ``compute fn`` (along with additional arguments ``*compute_args`` and ``**compute_kwargs``), then applies the returned value to :meth:`.Bot.answerInlineQuery` to answer the in...
Configure a: class:. Listener to capture callback query
def configure(self, listener): """ Configure a :class:`.Listener` to capture callback query """ listener.capture([ lambda msg: flavor(msg) == 'callback_query', {'message': self._chat_origin_included} ]) listener.capture([ lambda msg: f...
: param send_func: a function that sends messages such as: meth:. Bot. send \ *
def augment_send(self, send_func): """ :param send_func: a function that sends messages, such as :meth:`.Bot.send\*` :return: a function that wraps around ``send_func`` and examines whether the sent message contains an inline keyboard with callback data. If s...
: param delete_func: a function that deletes messages such as: meth:. Bot. deleteMessage
def augment_delete(self, delete_func): """ :param delete_func: a function that deletes messages, such as :meth:`.Bot.deleteMessage` :return: a function that wraps around ``delete_func`` and stops capturing callback query originating from that deleted message....
: return: a proxy to bot with these modifications:
def augment_bot(self, bot): """ :return: a proxy to ``bot`` with these modifications: - all ``send*`` methods augmented by :meth:`augment_send` - all ``edit*`` methods augmented by :meth:`augment_edit` - ``deleteMessage()`` augmented by :meth:`augment_del...
Refresh timeout timer
def refresh(self): """ Refresh timeout timer """ try: if self._timeout_event: self._scheduler.cancel(self._timeout_event) # Timeout event has been popped from queue prematurely except exception.EventNotFound: pass # Ensure a new event is ...
: return: a function wrapping handler to refresh timer for every non - event message
def augment_on_message(self, handler): """ :return: a function wrapping ``handler`` to refresh timer for every non-event message """ def augmented(msg): # Reset timer if this is an external message is_event(msg) or self.refresh() ...
: return: a function wrapping handler to cancel timeout event
def augment_on_close(self, handler): """ :return: a function wrapping ``handler`` to cancel timeout event """ def augmented(ex): try: if self._timeout_event: self._scheduler.cancel(self._timeout_event) self._...
Configure a: class:. Listener to capture events with this object s event space and source id.
def configure(self, listener): """ Configure a :class:`.Listener` to capture events with this object's event space and source id. """ listener.capture([{re.compile('^_.+'): {'source': {'space': self._event_space, 'id': self._source_id}}}])
Marshall flavor and data into a standard event.
def make_event_data(self, flavor, data): """ Marshall ``flavor`` and ``data`` into a standard event. """ if not flavor.startswith('_'): raise ValueError('Event flavor must start with _underscore') d = {'source': {'space': self._event_space, 'id': self._source_id}} ...
Schedule an event to be emitted at a certain time.
def event_at(self, when, data_tuple): """ Schedule an event to be emitted at a certain time. :param when: an absolute timestamp :param data_tuple: a 2-tuple (flavor, data) :return: an event object, useful for cancelling. """ return self._base.event_at(when, self....
Schedule an event to be emitted after a delay.
def event_later(self, delay, data_tuple): """ Schedule an event to be emitted after a delay. :param delay: number of seconds :param data_tuple: a 2-tuple (flavor, data) :return: an event object, useful for cancelling. """ return self._base.event_later(delay, self...
Apply key function to msg to obtain a key. Return the routing table entry.
def map(self, msg): """ Apply key function to ``msg`` to obtain a key. Return the routing table entry. """ k = self.key_function(msg) key = k[0] if isinstance(k, (tuple, list)) else k return self.routing_table[key]
Apply key function to msg to obtain a key look up routing table to obtain a handler function then call the handler function with positional and keyword arguments if any is returned by the key function.
def route(self, msg, *aa, **kw): """ Apply key function to ``msg`` to obtain a key, look up routing table to obtain a handler function, then call the handler function with positional and keyword arguments, if any is returned by the key function. ``*aa`` and ``**kw`` are dummy pl...
Format text as HTML. Also take care of escaping special characters. Returned value can be passed to: meth:. Bot. sendMessage with appropriate parse_mode.
def apply_entities_as_html(text, entities): """ Format text as HTML. Also take care of escaping special characters. Returned value can be passed to :meth:`.Bot.sendMessage` with appropriate ``parse_mode``. :param text: plain text :param entities: a list of `MessageEntity <https...
: return: a delegator function that returns a coroutine object by calling corofunc ( seed_tuple * args ** kwargs ).
def call(corofunc, *args, **kwargs): """ :return: a delegator function that returns a coroutine object by calling ``corofunc(seed_tuple, *args, **kwargs)``. """ corofunc = _ensure_coroutine_function(corofunc) def f(seed_tuple): return corofunc(seed_tuple, *args, **kwargs) ...
See: https:// core. telegram. org/ bots/ api#sendphoto
async def sendPhoto(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bot...
See: https:// core. telegram. org/ bots/ api#sendaudio
async def sendAudio(self, chat_id, audio, caption=None, parse_mode=None, duration=None, performer=None, title=None, disable_notification=None, reply_to_...
See: https:// core. telegram. org/ bots/ api#editmessagelivelocation
async def editMessageLiveLocation(self, msg_identifier, latitude, longitude, reply_markup=None): """ See: https://core.telegram.org/bots/api#editmessagelivelocation :param msg_identifier: Same as in :meth:`.Bot.editMessageText` """ p = _stri...
See: https:// core. telegram. org/ bots/ api#getfile
async def getFile(self, file_id): """ See: https://core.telegram.org/bots/api#getfile """ p = _strip(locals()) return await self._api_request('getFile', _rectify(p))
See: https:// core. telegram. org/ bots/ api#kickchatmember
async def kickChatMember(self, chat_id, user_id, until_date=None): """ See: https://core.telegram.org/bots/api#kickchatmember """ p = _strip(locals()) return await self._api_request('kickChatMember', _rectify(p))
See: https:// core. telegram. org/ bots/ api#restrictchatmember
async def restrictChatMember(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, c...
See: https:// core. telegram. org/ bots/ api#setchattitle
async def setChatTitle(self, chat_id, title): """ See: https://core.telegram.org/bots/api#setchattitle """ p = _strip(locals()) return await self._api_request('setChatTitle', _rectify(p))
See: https:// core. telegram. org/ bots/ api#setchatdescription
async def setChatDescription(self, chat_id, description=None): """ See: https://core.telegram.org/bots/api#setchatdescription """ p = _strip(locals()) return await self._api_request('setChatDescription', _rectify(p))
See: https:// core. telegram. org/ bots/ api#pinchatmessage
async def pinChatMessage(self, chat_id, message_id, disable_notification=None): """ See: https://core.telegram.org/bots/api#pinchatmessage """ p = _strip(locals()) return await self._api_request('pinChatMessage', _rectify(p))
See: https:// core. telegram. org/ bots/ api#unpinchatmessage
async def unpinChatMessage(self, chat_id): """ See: https://core.telegram.org/bots/api#unpinchatmessage """ p = _strip(locals()) return await self._api_request('unpinChatMessage', _rectify(p))
See: https:// core. telegram. org/ bots/ api#getchatmember
async def getChatMember(self, chat_id, user_id): """ See: https://core.telegram.org/bots/api#getchatmember """ p = _strip(locals()) return await self._api_request('getChatMember', _rectify(p))
See: https:// core. telegram. org/ bots/ api#setchatstickerset
async def setChatStickerSet(self, chat_id, sticker_set_name): """ See: https://core.telegram.org/bots/api#setchatstickerset """ p = _strip(locals()) return await self._api_request('setChatStickerSet', _rectify(p))
See: https:// core. telegram. org/ bots/ api#deletechatstickerset
async def deleteChatStickerSet(self, chat_id): """ See: https://core.telegram.org/bots/api#deletechatstickerset """ p = _strip(locals()) return await self._api_request('deleteChatStickerSet', _rectify(p))
See: https:// core. telegram. org/ bots/ api#answercallbackquery
async def answerCallbackQuery(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): """ See: https://core.telegram.org/bots/api#answercallbackquery "...
See: https:// core. telegram. org/ bots/ api#deletemessage
async def deleteMessage(self, msg_identifier): """ See: https://core.telegram.org/bots/api#deletemessage :param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.aio.Bot.editMessageText`, except this method does not work on inline messages. """ ...
See: https:// core. telegram. org/ bots/ api#sendsticker
async def sendSticker(self, chat_id, sticker, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bots/api#sendsticker :param sticker: Same as ``photo`` in :meth...
See: https:// core. telegram. org/ bots/ api#getstickerset
async def getStickerSet(self, name): """ See: https://core.telegram.org/bots/api#getstickerset """ p = _strip(locals()) return await self._api_request('getStickerSet', _rectify(p))
See: https:// core. telegram. org/ bots/ api#deletestickerfromset
async def deleteStickerFromSet(self, sticker): """ See: https://core.telegram.org/bots/api#deletestickerfromset """ p = _strip(locals()) return await self._api_request('deleteStickerFromSet', _rectify(p))
See: https:// core. telegram. org/ bots/ api#answerinlinequery
async def answerInlineQuery(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None):...
See: https:// core. telegram. org/ bots/ api#getupdates
async def getUpdates(self, offset=None, limit=None, timeout=None, allowed_updates=None): """ See: https://core.telegram.org/bots/api#getupdates """ p = _strip(locals()) return await self._api_requ...
See: https:// core. telegram. org/ bots/ api#setwebhook
async def setWebhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None): """ See: https://core.telegram.org/bots/api#setwebhook """ p = _strip(locals(), more=['certificate']) ...
Download a file to local disk.
async def download_file(self, file_id, dest): """ Download a file to local disk. :param dest: a path or a ``file`` object """ f = await self.getFile(file_id) try: d = dest if isinstance(dest, io.IOBase) else open(dest, 'wb') session, request = a...
Return a task to constantly getUpdates or pull updates from a queue. Apply handler to every message received.
async def message_loop(self, handler=None, relax=0.1, timeout=20, allowed_updates=None, source=None, ordered=True, maxhold=3): """ Return a task to constantly ``getUpdates`` or pull updates from a queue. Apply ``handler`` to every message rec...
Gather proxies from the providers without checking.
async def grab(self, *, countries=None, limit=0): """Gather proxies from the providers without checking. :param list countries: (optional) List of ISO country codes where should be located proxies :param int limit: (optional) The maximum number of proxies ...
Gather and check proxies from providers or from a passed data.
async def find( self, *, types=None, data=None, countries=None, post=False, strict=False, dnsbl=None, limit=0, **kwargs ): """Gather and check proxies from providers or from a passed data. :ref:`Example of usage <proxyb...
Start a local proxy server.
def serve(self, host='127.0.0.1', port=8888, limit=100, **kwargs): """Start a local proxy server. The server distributes incoming requests to a pool of found proxies. When the server receives an incoming request, it chooses the optimal proxy (based on the percentage of errors and avera...
Looking for proxies in the passed data.
async def _load(self, data, check=True): """Looking for proxies in the passed data. Transform the passed data from [raw string | file-like object | list] to set {(host, port), ...}: {('192.168.0.1', '80'), } """ log.debug('Load proxies from the raw data') if isinstance(d...
Stop all tasks and the local proxy server if it s running.
def stop(self): """Stop all tasks, and the local proxy server if it's running.""" self._done() if self._server: self._server.stop() self._server = None log.info('Stop!')
Show statistics on the found proxies.
def show_stats(self, verbose=False, **kwargs): """Show statistics on the found proxies. Useful for debugging, but you can also use if you're interested. :param verbose: Flag indicating whether to print verbose stats .. deprecated:: 0.2.0 Use :attr:`verbose` instead of :att...
Save proxies to a file.
async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break f.write('%s:%d\n' % (proxy.host, proxy.port))
Return geo information about IP address.
def get_ip_info(ip): """Return geo information about IP address. `code` - ISO country code `name` - Full name of country `region_code` - ISO region code `region_name` - Full name of region `city_name` - Full name of city """ # from pprint import pprint ...
Return real external IP address.
async def get_real_ext_ip(self): """Return real external IP address.""" while self._ip_hosts: try: timeout = aiohttp.ClientTimeout(total=self._timeout) async with aiohttp.ClientSession( timeout=timeout, loop=self._loop ) as ...
Return resolving IP address ( es ) from host name.
async def resolve( self, host, port=80, family=None, qtype='A', logging=True ): """Return resolving IP address(es) from host name.""" if self.host_is_ip(host): return host _host = self._cached_hosts.get(host) if _host: return _host resp = awa...
Asynchronously create a: class: Proxy object.
async def create(cls, host, *args, **kwargs): """Asynchronously create a :class:`Proxy` object. :param str host: A passed host can be a domain or IP address. If the host is a domain, try to resolve it :param str \*args: (optional) Positional arguments that :...
Error rate: from 0 to 1.
def error_rate(self): """Error rate: from 0 to 1. For example: 0.7 = 70% requests ends with error. :rtype: float .. versionadded:: 0.2.0 """ if not self.stat['requests']: return 0 return round( sum(self.stat['errors'].values()) / self.st...
Return supported schemes.
def schemes(self): """Return supported schemes.""" if not self._schemes: _schemes = [] if self.types.keys() & _HTTP_PROTOS: _schemes.append('HTTP') if self.types.keys() & _HTTPS_PROTOS: _schemes.append('HTTPS') self._schemes...
The average connection/ response time.
def avg_resp_time(self): """The average connection/response time. :rtype: float """ if not self._runtimes: return 0 return round(sum(self._runtimes) / len(self._runtimes), 2)
Return the proxy s properties in JSON format.
def as_json(self): """Return the proxy's properties in JSON format. :rtype: dict """ info = { 'host': self.host, 'port': self.port, 'geo': { 'country': {'code': self._geo.code, 'name': self._geo.name}, 'region': { ...
Receive proxies from the provider and return them.
async def get_proxies(self): """Receive proxies from the provider and return them. :return: :attr:`.proxies` """ log.debug('Try to get proxies from %s' % self.domain) async with aiohttp.ClientSession( headers=get_headers(), cookies=self._cookies, loop=self._loop ...
Save proxies to a file.
async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break proto = 'https' if 'HTTPS' in proxy.types else 'http' row = '%s://%s:%d\n' % (pr...
Updates global configuration settings with given values.
def update(self, **kwargs): """Updates global configuration settings with given values. First checks if given configuration values differ from current values. If any of the configuration values changed, generates a change event. Currently we generate change event for any configuration c...
Converts binary representation label to integer.
def label_from_bin(buf): """ Converts binary representation label to integer. :param buf: Binary representation of label. :return: MPLS Label and BoS bit. """ mpls_label = type_desc.Int3.to_user(six.binary_type(buf)) return mpls_label >> 4, mpls_label & 1
Removes VRF table associated with given vrf_conf.
def on_remove_vrf_conf(self, evt): """Removes VRF table associated with given `vrf_conf`. Cleans up other links to this table as well. """ vrf_conf = evt.value # Detach VrfConf change listener. vrf_conf.remove_listener(VrfConf.VRF_CHG_EVT, self.on_chg_vrf_conf) ...
Event handler for new VrfConf.
def on_add_vrf_conf(self, evt): """Event handler for new VrfConf. Creates a VrfTable to store routing information related to new Vrf. Also arranges for related paths to be imported to this VrfTable. """ vrf_conf = evt.value route_family = vrf_conf.route_family as...
Parses family and prefix in Zebra format.
def _parse_zebra_family_prefix(buf): """ Parses family and prefix in Zebra format. """ (family,) = struct.unpack_from(_ZEBRA_FAMILY_FMT, buf) rest = buf[_ZEBRA_FAMILY_SIZE:] if socket.AF_INET == family: (prefix, p_len) = struct.unpack_from(_ZEBRA_IPV4_PREFIX_FMT, rest) prefix = ...
Serializes family and prefix in Zebra format.
def _serialize_zebra_family_prefix(prefix): """ Serializes family and prefix in Zebra format. """ if ip.valid_ipv4(prefix): family = socket.AF_INET # fixup prefix_addr, prefix_num = prefix.split('/') return family, struct.pack( _ZEBRA_FAMILY_IPV4_PREFIX_FMT, ...
Returns True if the given MAC address is valid.
def is_valid_mac(mac): """Returns True if the given MAC address is valid. The given MAC address should be a colon hexadecimal notation string. Samples: - valid address: aa:bb:cc:dd:ee:ff, 11:22:33:44:55:66 - invalid address: aa:bb:cc:dd, 11-22-33-44-55-66, etc. """ return bool(re.m...
Returns True if * prefix * is a valid IPv4 or IPv6 address prefix.
def is_valid_ip_prefix(prefix, bits): """Returns True if *prefix* is a valid IPv4 or IPv6 address prefix. *prefix* should be a number between 0 to *bits* length. """ try: # Prefix should be a number prefix = int(prefix) except ValueError: return False # Prefix should be...
Returns True if * ipv4_prefix * is a valid prefix with mask.
def is_valid_ipv4_prefix(ipv4_prefix): """Returns True if *ipv4_prefix* is a valid prefix with mask. Samples: - valid prefix: 1.1.1.0/32, 244.244.244.1/10 - invalid prefix: 255.2.2.2/2, 2.2.2/22, etc. """ if not isinstance(ipv4_prefix, str): return False tokens = ipv4_prefi...
Returns True if given ipv6_prefix is a valid IPv6 prefix.
def is_valid_ipv6_prefix(ipv6_prefix): """Returns True if given `ipv6_prefix` is a valid IPv6 prefix.""" # Validate input type if not isinstance(ipv6_prefix, str): return False tokens = ipv6_prefix.split('/') if len(tokens) != 2: return False # Validate address/mask and return...
Returns True if given prefix is a string represent vpnv4 prefix.
def is_valid_vpnv4_prefix(prefix): """Returns True if given prefix is a string represent vpnv4 prefix. Vpnv4 prefix is made up of RD:Ipv4, where RD is represents route distinguisher and Ipv4 represents valid dot-decimal ipv4 notation string. """ if not isinstance(prefix, str): return False ...
Returns True if given prefix is a string represent vpnv6 prefix.
def is_valid_vpnv6_prefix(prefix): """Returns True if given prefix is a string represent vpnv6 prefix. Vpnv6 prefix is made up of RD:Ipv6, where RD is represents route distinguisher and Ipv6 represents valid colon hexadecimal notation string. """ if not isinstance(prefix, str): return False...
Validates label according to MPLS label rules
def is_valid_mpls_label(label): """Validates `label` according to MPLS label rules RFC says: This 20-bit field. A value of 0 represents the "IPv4 Explicit NULL Label". A value of 1 represents the "Router Alert Label". A value of 2 represents the "IPv6 Explicit NULL Label". A value of 3 repr...
Returns True if the given value is a list of valid MPLS labels.
def is_valid_mpls_labels(labels): """Returns True if the given value is a list of valid MPLS labels. """ if not isinstance(labels, (list, tuple)): return False for label in labels: if not is_valid_mpls_label(label): return False return True
Validates * attr * as string representation of RT or SOO.
def is_valid_ext_comm_attr(attr): """Validates *attr* as string representation of RT or SOO. Returns True if *attr* is as per our convention of RT or SOO, else False. Our convention is to represent RT/SOO is a string with format: *global_admin_part:local_admin_path* """ if not isinstance(attr, ...
Returns True if the given EVPN Ethernet SegmentEthernet ID is valid.
def is_valid_esi(esi): """Returns True if the given EVPN Ethernet SegmentEthernet ID is valid.""" if isinstance(esi, numbers.Integral): return 0 <= esi <= 0xffffffffffffffffff return isinstance(esi, dict)