_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q800
PubSubClient.retract
train
def retract(self, jid, node, id_, *, notify=False): """ Retract a previously published item from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to send a notify from. :type node: :class:`str` :param id_: The ID of the item to retract. :type id_: :class:`str` :param notify: Flag indicating whether subscribers shall be notified about the retraction. :type notify: :class:`bool` :raises aioxmpp.errors.XMPPError: as returned by the service Retract an item previously published to `node` at `jid`. `id_` must be the ItemID of the item to retract. If `notify` is set to true, notifications will be generated (by setting the `notify` attribute on the retraction request). """ retract = pubsub_xso.Retract() retract.node = node item = pubsub_xso.Item() item.id_ = id_ retract.item = item retract.notify = notify iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( retract ) yield from self.client.send(iq)
python
{ "resource": "" }
q801
PubSubClient.create
train
def create(self, jid, node=None): """ Create a new node at a service. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to create. :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The name of the created node. :rtype: :class:`str` If `node` is :data:`None`, an instant node is created (see :xep:`60`). The server may not support or allow the creation of instant nodes. Return the actual `node` identifier. """ create = pubsub_xso.Create() create.node = node iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.Request(create) ) response = yield from self.client.send(iq) if response is not None and response.payload.node is not None: return response.payload.node return node
python
{ "resource": "" }
q802
PubSubClient.delete
train
def delete(self, jid, node, *, redirect_uri=None): """ Delete an existing node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to delete. :type node: :class:`str` or :data:`None` :param redirect_uri: A URI to send to subscribers to indicate a replacement for the deleted node. :type redirect_uri: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service Optionally, a `redirect_uri` can be given. The `redirect_uri` will be sent to subscribers in the message notifying them about the node deletion. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerDelete( node, redirect_uri=redirect_uri ) ) ) yield from self.client.send(iq)
python
{ "resource": "" }
q803
PubSubClient.get_nodes
train
def get_nodes(self, jid, node=None): """ Request all nodes at a service or collection node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the collection node to query :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The list of nodes at the service or collection node. :rtype: :class:`~collections.abc.Sequence` of tuples consisting of the node name and its description. Request the nodes available at `jid`. If `node` is not :data:`None`, the request returns the children of the :xep:`248` collection node `node`. Make sure to check for the appropriate server feature first. Return a list of tuples consisting of the node names and their description (if available, otherwise :data:`None`). If more information is needed, use :meth:`.DiscoClient.get_items` directly. Only nodes whose :attr:`~.disco.xso.Item.jid` match the `jid` are returned. """ response = yield from self._disco.query_items( jid, node=node, ) result = [] for item in response.items: if item.jid != jid: continue result.append(( item.node, item.name, )) return result
python
{ "resource": "" }
q804
PubSubClient.get_node_affiliations
train
def get_node_affiliations(self, jid, node): """ Return the affiliations of other jids at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to query :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service. :rtype: :class:`.xso.OwnerRequest` The affiliations are returned as :class:`.xso.OwnerRequest` instance whose :attr:`~.xso.OwnerRequest.payload` is a :class:`.xso.OwnerAffiliations` instance. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.GET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerAffiliations(node), ) ) return (yield from self.client.send(iq))
python
{ "resource": "" }
q805
PubSubClient.change_node_affiliations
train
def change_node_affiliations(self, jid, node, affiliations_to_set): """ Update the affiliations at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param affiliations_to_set: The affiliations to set at the node. :type affiliations_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to affiliate and the affiliation to use. :raises aioxmpp.errors.XMPPError: as returned by the service `affiliations_to_set` must be an iterable of pairs (`jid`, `affiliation`), where the `jid` indicates the JID for which the `affiliation` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerAffiliations( node, affiliations=[ pubsub_xso.OwnerAffiliation( jid, affiliation ) for jid, affiliation in affiliations_to_set ] ) ) ) yield from self.client.send(iq)
python
{ "resource": "" }
q806
PubSubClient.change_node_subscriptions
train
def change_node_subscriptions(self, jid, node, subscriptions_to_set): """ Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to (un)subscribe and the subscription level to use. :raises aioxmpp.errors.XMPPError: as returned by the service `subscriptions_to_set` must be an iterable of pairs (`jid`, `subscription`), where the `jid` indicates the JID for which the `subscription` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerSubscriptions( node, subscriptions=[ pubsub_xso.OwnerSubscription( jid, subscription ) for jid, subscription in subscriptions_to_set ] ) ) ) yield from self.client.send(iq)
python
{ "resource": "" }
q807
PubSubClient.purge
train
def purge(self, jid, node): """ Delete all items from a node. :param jid: JID of the PubSub service :param node: Name of the PubSub node :type node: :class:`str` Requires :attr:`.xso.Feature.PURGE`. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerPurge( node ) ) ) yield from self.client.send(iq)
python
{ "resource": "" }
q808
Child.from_events
train
def from_events(self, instance, ev_args, ctx): """ Detect the object to instanciate from the arguments `ev_args` of the ``"start"`` event. The new object is stored at the corresponding descriptor attribute on `instance`. This method is suspendable. """ obj = yield from self._process(instance, ev_args, ctx) self.__set__(instance, obj) return obj
python
{ "resource": "" }
q809
XSOParser.add_class
train
def add_class(self, cls, callback): """ Add a class `cls` for parsing as root level element. When an object of `cls` type has been completely parsed, `callback` is called with the object as argument. """ if cls.TAG in self._tag_map: raise ValueError( "duplicate tag: {!r} is already handled by {}".format( cls.TAG, self._tag_map[cls.TAG])) self._class_map[cls] = callback self._tag_map[cls.TAG] = (cls, callback)
python
{ "resource": "" }
q810
check_bidi
train
def check_bidi(chars): """ Check proper bidirectionality as per stringprep. Operates on a list of unicode characters provided in `chars`. """ # the empty string is valid, as it cannot violate the RandALCat constraints if not chars: return # first_is_RorAL = unicodedata.bidirectional(chars[0]) in {"R", "AL"} # if first_is_RorAL: has_RandALCat = any(is_RandALCat(c) for c in chars) if not has_RandALCat: return has_LCat = any(is_LCat(c) for c in chars) if has_LCat: raise ValueError("L and R/AL characters must not occur in the same" " string") if not is_RandALCat(chars[0]) or not is_RandALCat(chars[-1]): raise ValueError("R/AL string must start and end with R/AL character.")
python
{ "resource": "" }
q811
check_prohibited_output
train
def check_prohibited_output(chars, bad_tables): """ Check against prohibited output, by checking whether any of the characters from `chars` are in any of the `bad_tables`. Operates in-place on a list of code points from `chars`. """ violator = check_against_tables(chars, bad_tables) if violator is not None: raise ValueError("Input contains invalid unicode codepoint: " "U+{:04x}".format(ord(violator)))
python
{ "resource": "" }
q812
check_unassigned
train
def check_unassigned(chars, bad_tables): """ Check that `chars` does not contain any unassigned code points as per the given list of `bad_tables`. Operates on a list of unicode code points provided in `chars`. """ bad_tables = ( stringprep.in_table_a1,) violator = check_against_tables(chars, bad_tables) if violator is not None: raise ValueError("Input contains unassigned code point: " "U+{:04x}".format(ord(violator)))
python
{ "resource": "" }
q813
AvatarSet.add_avatar_image
train
def add_avatar_image(self, mime_type, *, id_=None, image_bytes=None, width=None, height=None, url=None, nbytes=None): """ Add a source of the avatar image. All sources of an avatar image added to an avatar set must be *the same image*, in different formats and sizes. :param mime_type: The MIME type of the avatar image. :param id_: The SHA1 of the image data. :param nbytes: The size of the image data in bytes. :param image_bytes: The image data, this must be supplied only in one call. :param url: The URL of the avatar image. :param height: The height of the image in pixels (optional). :param width: The width of the image in pixels (optional). `id_` and `nbytes` may be omitted if and only if `image_data` is given and `mime_type` is ``image/png``. If they are supplied *and* image data is given, they are checked to match the image data. It is the caller's responsibility to assure that the provided links exist and the files have the correct SHA1 sums. """ if mime_type == "image/png": if image_bytes is not None: if self._image_bytes is not None: raise RuntimeError( "Only one avatar image may be published directly." ) sha1 = hashlib.sha1() sha1.update(image_bytes) id_computed = normalize_id(sha1.hexdigest()) if id_ is not None: id_ = normalize_id(id_) if id_ != id_computed: raise RuntimeError( "The given id does not match the SHA1 of " "the image data." ) else: id_ = id_computed nbytes_computed = len(image_bytes) if nbytes is not None: if nbytes != nbytes_computed: raise RuntimeError( "The given length does not match the length " "of the image data." ) else: nbytes = nbytes_computed self._image_bytes = image_bytes self._png_id = id_ if image_bytes is None and url is None: raise RuntimeError( "Either the image bytes or an url to retrieve the avatar " "image must be given." ) if nbytes is None: raise RuntimeError( "Image data length is not given an not inferable " "from the other arguments." ) if id_ is None: raise RuntimeError( "The SHA1 of the image data is not given an not inferable " "from the other arguments." ) if image_bytes is not None and mime_type != "image/png": raise RuntimeError( "The image bytes can only be given for image/png data." ) self._metadata.info[mime_type].append( avatar_xso.Info( id_=id_, mime_type=mime_type, nbytes=nbytes, width=width, height=height, url=url ) )
python
{ "resource": "" }
q814
AvatarService.get_avatar_metadata
train
def get_avatar_metadata(self, jid, *, require_fresh=False, disable_pep=False): """ Retrieve a list of avatar descriptors. :param jid: the JID for which to retrieve the avatar metadata. :type jid: :class:`aioxmpp.JID` :param require_fresh: if true, do not return results from the avatar metadata chache, but retrieve them again from the server. :type require_fresh: :class:`bool` :param disable_pep: if true, do not try to retrieve the avatar via pep, only try the vCard fallback. This usually only useful when querying avatars via MUC, where the PEP request would be invalid (since it would be for a full jid). :type disable_pep: :class:`bool` :returns: an iterable of avatar descriptors. :rtype: a :class:`list` of :class:`~aioxmpp.avatar.service.AbstractAvatarDescriptor` instances Returning an empty list means that the avatar not set. We mask a :class:`XMPPCancelError` in the case that it is ``feature-not-implemented`` or ``item-not-found`` and return an empty list of avatar descriptors, since this is semantically equivalent to not having an avatar. .. note:: It is usually an error to get the avatar for a full jid, normally, the avatar is set for the bare jid of a user. The exception are vCard avatars over MUC, where the IQ requests for the vCard may be translated by the MUC server. It is recommended to use the `disable_pep` option in that case. """ if require_fresh: self._metadata_cache.pop(jid, None) else: try: return self._metadata_cache[jid] except KeyError: pass if disable_pep: metadata = [] else: metadata = yield from self._get_avatar_metadata_pep(jid) # try the vcard fallback, note: we don't try this # if the PEP avatar is disabled! if not metadata and jid not in self._has_pep_avatar: metadata = yield from self._get_avatar_metadata_vcard(jid) # if a notify was fired while we waited for the results, then # use the version in the cache, this will mitigate the race # condition because if our version is actually newer we will # soon get another notify for this version change! if jid not in self._metadata_cache: self._update_metadata(jid, metadata) return self._metadata_cache[jid]
python
{ "resource": "" }
q815
AvatarService.publish_avatar_set
train
def publish_avatar_set(self, avatar_set): """ Make `avatar_set` the current avatar of the jid associated with this connection. If :attr:`synchronize_vcard` is true and PEP is available the vCard is only synchronized if the PEP update is successful. This means publishing the ``image/png`` avatar data and the avatar metadata set in pubsub. The `avatar_set` must be an instance of :class:`AvatarSet`. If :attr:`synchronize_vcard` is true the avatar is additionally published in the user vCard. """ id_ = avatar_set.png_id done = False with (yield from self._publish_lock): if (yield from self._pep.available()): yield from self._pep.publish( namespaces.xep0084_data, avatar_xso.Data(avatar_set.image_bytes), id_=id_ ) yield from self._pep.publish( namespaces.xep0084_metadata, avatar_set.metadata, id_=id_ ) done = True if self._synchronize_vcard: my_vcard = yield from self._vcard.get_vcard() my_vcard.set_photo_data("image/png", avatar_set.image_bytes) self._vcard_id = avatar_set.png_id yield from self._vcard.set_vcard(my_vcard) self._presence_server.resend_presence() done = True if not done: raise RuntimeError( "failed to publish avatar: no protocol available" )
python
{ "resource": "" }
q816
AvatarService.disable_avatar
train
def disable_avatar(self): """ Temporarily disable the avatar. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled (even if disabling the PEP avatar fails). This is done by setting the avatar metadata node empty and if :attr:`synchronize_vcard` is true, downloading the vCard, removing the avatar data and re-uploading the vCard. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks. """ with (yield from self._publish_lock): todo = [] if self._synchronize_vcard: todo.append(self._disable_vcard_avatar()) if (yield from self._pep.available()): todo.append(self._pep.publish( namespaces.xep0084_metadata, avatar_xso.Metadata() )) yield from gather_reraise_multi(*todo, message="disable_avatar")
python
{ "resource": "" }
q817
AvatarService.wipe_avatar
train
def wipe_avatar(self): """ Remove all avatar data stored on the server. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled even if disabling the PEP avatar fails. This is equivalent to :meth:`disable_avatar` for vCard-based avatars, but will also remove the data PubSub node for PEP avatars. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks. """ @asyncio.coroutine def _wipe_pep_avatar(): yield from self._pep.publish( namespaces.xep0084_metadata, avatar_xso.Metadata() ) yield from self._pep.publish( namespaces.xep0084_data, avatar_xso.Data(b'') ) with (yield from self._publish_lock): todo = [] if self._synchronize_vcard: todo.append(self._disable_vcard_avatar()) if (yield from self._pep.available()): todo.append(_wipe_pep_avatar()) yield from gather_reraise_multi(*todo, message="wipe_avatar")
python
{ "resource": "" }
q818
BlockingClient.block_jids
train
def block_jids(self, jids_to_block): """ Add the JIDs in the sequence `jids_to_block` to the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_block: return cmd = blocking_xso.BlockCommand(jids_to_block) iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=cmd, ) yield from self.client.send(iq)
python
{ "resource": "" }
q819
BlockingClient.unblock_jids
train
def unblock_jids(self, jids_to_unblock): """ Remove the JIDs in the sequence `jids_to_block` from the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_unblock: return cmd = blocking_xso.UnblockCommand(jids_to_unblock) iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=cmd, ) yield from self.client.send(iq)
python
{ "resource": "" }
q820
DescriptorClass._register_descriptor_keys
train
def _register_descriptor_keys(self, descriptor, keys): """ Register the given descriptor keys for the given descriptor at the class. :param descriptor: The descriptor for which the `keys` shall be registered. :type descriptor: :class:`AbstractDescriptor` instance :param keys: An iterable of descriptor keys :raises TypeError: if the specified keys are already handled by a descriptor. :raises TypeError: if this class has subclasses or if it is not the :attr:`~AbstractDescriptor.root_class` of the given descriptor. If the method raises, the caller must assume that registration was not successful. .. note:: The intended audience for this method are developers of :class:`AbstractDescriptor` subclasses, which are generally only expected to live in the :mod:`aioxmpp` package. Thus, you should not expect this API to be stable. If you have a use-case for using this function outside of :mod:`aioxmpp`, please let me know through the usual issue reporting means. """ if descriptor.root_class is not self or self.__subclasses__(): raise TypeError( "descriptors cannot be modified on classes with subclasses" ) meta = type(self) descriptor_info = meta._upcast_descriptor_map( self.DESCRIPTOR_MAP, "{}.{}".format(self.__module__, self.__qualname__), ) # this would raise on conflict meta._merge_descriptors( descriptor_info, [ (key, (descriptor, "<added via _register_descriptor_keys>")) for key in keys ] ) for key in keys: self.DESCRIPTOR_MAP[key] = descriptor
python
{ "resource": "" }
q821
FormClass.from_xso
train
def from_xso(self, xso): """ Construct and return an instance from the given `xso`. .. note:: This is a static method (classmethod), even though sphinx does not document it as such. :param xso: A :xep:`4` data form :type xso: :class:`~.Data` :raises ValueError: if the ``FORM_TYPE`` mismatches :raises ValueError: if field types mismatch :return: newly created instance of this class The fields from the given `xso` are matched against the fields on the form. Any matching field loads its data from the `xso` field. Fields which occur on the form template but not in the `xso` are skipped. Fields which occur in the `xso` but not on the form template are also skipped (but are re-emitted when the form is rendered as reply, see :meth:`~.Form.render_reply`). If the form template has a ``FORM_TYPE`` attribute and the incoming `xso` also has a ``FORM_TYPE`` field, a mismatch between the two values leads to a :class:`ValueError`. The field types of matching fields are checked. If the field type on the incoming XSO may not be upcast to the field type declared on the form (see :meth:`~.FieldType.allow_upcast`), a :class:`ValueError` is raised. If the :attr:`~.Data.type_` does not indicate an actual form (but rather a cancellation request or tabular result), :class:`ValueError` is raised. """ my_form_type = getattr(self, "FORM_TYPE", None) f = self() for field in xso.fields: if field.var == "FORM_TYPE": if (my_form_type is not None and field.type_ == forms_xso.FieldType.HIDDEN and field.values): if my_form_type != field.values[0]: raise ValueError( "mismatching FORM_TYPE ({!r} != {!r})".format( field.values[0], my_form_type, ) ) continue if field.var is None: continue key = fields.descriptor_ns, field.var try: descriptor = self.DESCRIPTOR_MAP[key] except KeyError: continue if (field.type_ is not None and not field.type_.allow_upcast(descriptor.FIELD_TYPE)): raise ValueError( "mismatching type ({!r} != {!r}) on field var={!r}".format( field.type_, descriptor.FIELD_TYPE, field.var, ) ) data = descriptor.__get__(f, self) data.load(field) f._recv_xso = xso return f
python
{ "resource": "" }
q822
PEPClient.claim_pep_node
train
def claim_pep_node(self, node_namespace, *, register_feature=True, notify=False): """ Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` as feature. :param notify: Whether to register the ``+notify`` feature to receive notification without explicit subscription. :raises RuntimeError: if a handler for `node_namespace` is already set. :returns: a :class:`~aioxmpp.pep.service.RegisteredPEPNode` instance representing the claim. .. seealso:: :class:`aioxmpp.pep.register_pep_node` a descriptor which can be used with :class:`~aioxmpp.service.Service` subclasses to claim a PEP node automatically. This registers `node_namespace` as feature for service discovery unless ``register_feature=False`` is passed. .. note:: For `notify` to work, it is required that :class:`aioxmpp.EntityCapsService` is loaded and that presence is re-sent soon after :meth:`~aioxmpp.EntityCapsService.on_ver_changed` fires. See the documentation of the class and the signal for details. """ if node_namespace in self._pep_node_claims: raise RuntimeError( "claiming already claimed node" ) registered_node = RegisteredPEPNode( self, node_namespace, register_feature=register_feature, notify=notify, ) finalizer = weakref.finalize( registered_node, weakref.WeakMethod(registered_node._unregister) ) # we cannot guarantee that disco is not cleared up already, # so we do not unclaim the feature on exit finalizer.atexit = False self._pep_node_claims[node_namespace] = registered_node return registered_node
python
{ "resource": "" }
q823
PEPClient.available
train
def available(self): """ Check whether we have a PEP identity associated with our account. """ disco_info = yield from self._disco_client.query_info( self.client.local_jid.bare() ) for item in disco_info.identities.filter(attrs={"category": "pubsub"}): if item.type_ == "pep": return True return False
python
{ "resource": "" }
q824
PEPClient.publish
train
def publish(self, node, data, *, id_=None, access_model=None): """ Publish an item `data` in the PubSub node `node` on the PEP service associated with the user's JID. :param node: The PubSub node to publish to. :param data: The item to publish. :type data: An XSO representing the paylaod. :param id_: The id the published item shall have. :param access_model: The access model to enforce on the node. Defaults to not enforcing any access model. :returns: The PubSub id of the published item or :data:`None` if it is unknown. :raises RuntimeError: if PEP is not supported. :raises RuntimeError: if `access_model` is set and `publish_options` is not supported by the server If no `id_` is given it is generated by the server (and may be returned). `access_model` defines a pre-condition on the access model used for the `node`. The valid values depend on the service; commonly useful ``"presence"`` (the default for PEP; allows access to anyone who can receive the presence) and ``"whitelist"`` (allows access only to a whitelist (which defaults to the own account only)). """ publish_options = None def autocreate_publish_options(): nonlocal publish_options if publish_options is None: publish_options = aioxmpp.forms.Data( aioxmpp.forms.DataType.SUBMIT ) publish_options.fields.append( aioxmpp.forms.Field( type_=aioxmpp.forms.FieldType.HIDDEN, var="FORM_TYPE", values=[ "http://jabber.org/protocol/pubsub#publish-options" ] ) ) return publish_options if access_model is not None: autocreate_publish_options() publish_options.fields.append(aioxmpp.forms.Field( var="pubsub#access_model", values=[access_model], )) yield from self._check_for_pep() return (yield from self._pubsub.publish( None, node, data, id_=id_, publish_options=publish_options ))
python
{ "resource": "" }
q825
RegisteredPEPNode.close
train
def close(self): """ Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`. """ if self._closed: return self._closed = True self._pep_service._unclaim(self.node_namespace) self._unregister()
python
{ "resource": "" }
q826
DjangoNode.full_clean
train
def full_clean(self, exclude, validate_unique=False): """ Validate node, on error raising ValidationErrors which can be handled by django forms :param exclude: :param validate_unique: Check if conflicting node exists in the labels indexes :return: """ # validate against neomodel try: self.deflate(self.__properties__, self) except DeflateError as e: raise ValidationError({e.property_name: e.msg}) except RequiredProperty as e: raise ValidationError({e.property_name: 'is required'})
python
{ "resource": "" }
q827
AbstractUser.email_user
train
def email_user(self, subject, message, from_email=None): """ Send an email to this User.""" send_mail(subject, message, from_email, [self.email])
python
{ "resource": "" }
q828
UserAdmin.activate_users
train
def activate_users(self, request, queryset): """ Activates the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active: user.activate() n += 1 self.message_user( request, _('Successfully activated %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS)
python
{ "resource": "" }
q829
UserAdmin.send_activation_email
train
def send_activation_email(self, request, queryset): """ Send activation emails for the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active and settings.USERS_VERIFY_EMAIL: send_activation_email(user=user, request=request) n += 1 self.message_user( request, _('Activation emails sent to %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS)
python
{ "resource": "" }
q830
UserManager.get_queryset
train
def get_queryset(self): """ Fixes get_query_set vs get_queryset for Django <1.6 """ try: qs = super(UserManager, self).get_queryset() except AttributeError: # pragma: no cover qs = super(UserManager, self).get_query_set() return qs
python
{ "resource": "" }
q831
Poller.is_ready
train
def is_ready(self): """Is Socket Ready. :rtype: tuple """ try: ready, _, _ = self.select.select([self.fileno], [], [], POLL_TIMEOUT) return bool(ready) except self.select.error as why: if why.args[0] != EINTR: self._exceptions.append(AMQPConnectionError(why)) return False
python
{ "resource": "" }
q832
IO.close
train
def close(self): """Close Socket. :return: """ self._wr_lock.acquire() self._rd_lock.acquire() try: self._running.clear() if self.socket: self._close_socket() if self._inbound_thread: self._inbound_thread.join(timeout=self._parameters['timeout']) self._inbound_thread = None self.poller = None self.socket = None finally: self._wr_lock.release() self._rd_lock.release()
python
{ "resource": "" }
q833
IO.open
train
def open(self): """Open Socket and establish a connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ self._wr_lock.acquire() self._rd_lock.acquire() try: self.data_in = EMPTY_BUFFER self._running.set() sock_addresses = self._get_socket_addresses() self.socket = self._find_address_and_connect(sock_addresses) self.poller = Poller(self.socket.fileno(), self._exceptions, timeout=self._parameters['timeout']) self._inbound_thread = self._create_inbound_thread() finally: self._wr_lock.release() self._rd_lock.release()
python
{ "resource": "" }
q834
IO.write_to_socket
train
def write_to_socket(self, frame_data): """Write data to the socket. :param str frame_data: :return: """ self._wr_lock.acquire() try: total_bytes_written = 0 bytes_to_send = len(frame_data) while total_bytes_written < bytes_to_send: try: if not self.socket: raise socket.error('connection/socket error') bytes_written = ( self.socket.send(frame_data[total_bytes_written:]) ) if bytes_written == 0: raise socket.error('connection/socket error') total_bytes_written += bytes_written except socket.timeout: pass except socket.error as why: if why.args[0] in (EWOULDBLOCK, EAGAIN): continue self._exceptions.append(AMQPConnectionError(why)) return finally: self._wr_lock.release()
python
{ "resource": "" }
q835
IO._close_socket
train
def _close_socket(self): """Shutdown and close the Socket. :return: """ try: self.socket.shutdown(socket.SHUT_RDWR) except (OSError, socket.error): pass self.socket.close()
python
{ "resource": "" }
q836
IO._get_socket_addresses
train
def _get_socket_addresses(self): """Get Socket address information. :rtype: list """ family = socket.AF_UNSPEC if not socket.has_ipv6: family = socket.AF_INET try: addresses = socket.getaddrinfo(self._parameters['hostname'], self._parameters['port'], family, socket.SOCK_STREAM) except socket.gaierror as why: raise AMQPConnectionError(why) return addresses
python
{ "resource": "" }
q837
IO._find_address_and_connect
train
def _find_address_and_connect(self, addresses): """Find and connect to the appropriate address. :param addresses: :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: socket.socket """ error_message = None for address in addresses: sock = self._create_socket(socket_family=address[0]) try: sock.connect(address[4]) except (IOError, OSError) as why: error_message = why.strerror continue return sock raise AMQPConnectionError( 'Could not connect to %s:%d error: %s' % ( self._parameters['hostname'], self._parameters['port'], error_message ) )
python
{ "resource": "" }
q838
IO._create_socket
train
def _create_socket(self, socket_family): """Create Socket. :param int socket_family: :rtype: socket.socket """ sock = socket.socket(socket_family, socket.SOCK_STREAM, 0) sock.settimeout(self._parameters['timeout'] or None) if self.use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( 'Python not compiled with support for TLSv1 or higher' ) sock = self._ssl_wrap_socket(sock) return sock
python
{ "resource": "" }
q839
IO._ssl_wrap_socket
train
def _ssl_wrap_socket(self, sock): """Wrap SSLSocket around the Socket. :param socket.socket sock: :rtype: SSLSocket """ context = self._parameters['ssl_options'].get('context') if context is not None: hostname = self._parameters['ssl_options'].get('server_hostname') return context.wrap_socket( sock, do_handshake_on_connect=True, server_hostname=hostname ) if 'ssl_version' not in self._parameters['ssl_options']: self._parameters['ssl_options']['ssl_version'] = ( compatibility.DEFAULT_SSL_VERSION ) return ssl.wrap_socket( sock, do_handshake_on_connect=True, **self._parameters['ssl_options'] )
python
{ "resource": "" }
q840
IO._create_inbound_thread
train
def _create_inbound_thread(self): """Internal Thread that handles all incoming traffic. :rtype: threading.Thread """ inbound_thread = threading.Thread(target=self._process_incoming_data, name=__name__) inbound_thread.daemon = True inbound_thread.start() return inbound_thread
python
{ "resource": "" }
q841
IO._process_incoming_data
train
def _process_incoming_data(self): """Retrieve and process any incoming data. :return: """ while self._running.is_set(): if self.poller.is_ready: self.data_in += self._receive() self.data_in = self._on_read_impl(self.data_in)
python
{ "resource": "" }
q842
IO._receive
train
def _receive(self): """Receive any incoming socket data. If an error is thrown, handle it and return an empty string. :return: data_in :rtype: bytes """ data_in = EMPTY_BUFFER try: data_in = self._read_from_socket() except socket.timeout: pass except (IOError, OSError) as why: if why.args[0] not in (EWOULDBLOCK, EAGAIN): self._exceptions.append(AMQPConnectionError(why)) self._running.clear() return data_in
python
{ "resource": "" }
q843
IO._read_from_socket
train
def _read_from_socket(self): """Read data from the socket. :rtype: bytes """ if not self.use_ssl: if not self.socket: raise socket.error('connection/socket error') return self.socket.recv(MAX_FRAME_SIZE) with self._rd_lock: if not self.socket: raise socket.error('connection/socket error') return self.socket.read(MAX_FRAME_SIZE)
python
{ "resource": "" }
q844
Heartbeat.start
train
def start(self, exceptions): """Start the Heartbeat Checker. :param list exceptions: :return: """ if not self._interval: return False self._running.set() with self._lock: self._threshold = 0 self._reads_since_check = 0 self._writes_since_check = 0 self._exceptions = exceptions LOGGER.debug('Heartbeat Checker Started') return self._start_new_timer()
python
{ "resource": "" }
q845
Heartbeat.stop
train
def stop(self): """Stop the Heartbeat Checker. :return: """ self._running.clear() with self._lock: if self._timer: self._timer.cancel() self._timer = None
python
{ "resource": "" }
q846
Heartbeat._check_for_life_signs
train
def _check_for_life_signs(self): """Check Connection for life signs. First check if any data has been sent, if not send a heartbeat to the remote server. If we have not received any data what so ever within two intervals, we need to raise an exception so that we can close the connection. :rtype: bool """ if not self._running.is_set(): return False if self._writes_since_check == 0: self.send_heartbeat_impl() self._lock.acquire() try: if self._reads_since_check == 0: self._threshold += 1 if self._threshold >= 2: self._running.clear() self._raise_or_append_exception() return False else: self._threshold = 0 finally: self._reads_since_check = 0 self._writes_since_check = 0 self._lock.release() return self._start_new_timer()
python
{ "resource": "" }
q847
Heartbeat._raise_or_append_exception
train
def _raise_or_append_exception(self): """The connection is presumably dead and we need to raise or append an exception. If we have a list for exceptions, append the exception and let the connection handle it, if not raise the exception here. :return: """ message = ( 'Connection dead, no heartbeat or data received in >= ' '%ds' % ( self._interval * 2 ) ) why = AMQPConnectionError(message) if self._exceptions is None: raise why self._exceptions.append(why)
python
{ "resource": "" }
q848
Heartbeat._start_new_timer
train
def _start_new_timer(self): """Create a timer that will be used to periodically check the connection for heartbeats. :return: """ if not self._running.is_set(): return False self._timer = self.timer_impl( interval=self._interval, function=self._check_for_life_signs ) self._timer.daemon = True self._timer.start() return True
python
{ "resource": "" }
q849
Queue.get
train
def get(self, queue, virtual_host='/'): """Get Queue details. :param queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUE % ( virtual_host, queue ) )
python
{ "resource": "" }
q850
Queue.list
train
def list(self, virtual_host='/', show_all=False): """List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ if show_all: return self.http_client.get(API_QUEUES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUES_VIRTUAL_HOST % virtual_host )
python
{ "resource": "" }
q851
Queue.bindings
train
def bindings(self, queue, virtual_host='/'): """Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_QUEUE_BINDINGS % ( virtual_host, queue ))
python
{ "resource": "" }
q852
Exchange.get
train
def get(self, exchange, virtual_host='/'): """Get Exchange details. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGE % ( virtual_host, exchange) )
python
{ "resource": "" }
q853
Exchange.list
train
def list(self, virtual_host='/', show_all=False): """List Exchanges. :param str virtual_host: Virtual host name :param bool show_all: List all Exchanges :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ if show_all: return self.http_client.get(API_EXCHANGES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGES_VIRTUAL_HOST % virtual_host )
python
{ "resource": "" }
q854
Exchange.bindings
train
def bindings(self, exchange, virtual_host='/'): """Get Exchange bindings. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_EXCHANGE_BINDINGS % ( virtual_host, exchange ))
python
{ "resource": "" }
q855
Connection.check_for_errors
train
def check_for_errors(self): """Check Connection for errors. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ if not self.exceptions: if not self.is_closed: return why = AMQPConnectionError('connection was closed') self.exceptions.append(why) self.set_state(self.CLOSED) self.close() raise self.exceptions[0]
python
{ "resource": "" }
q856
Connection.open
train
def open(self): """Open Connection. :raises AMQPConnectionError: Raises if the connection encountered an error. """ LOGGER.debug('Connection Opening') self.set_state(self.OPENING) self._exceptions = [] self._channels = {} self._last_channel_id = None self._io.open() self._send_handshake() self._wait_for_connection_state(state=Stateful.OPEN) self.heartbeat.start(self._exceptions) LOGGER.debug('Connection Opened')
python
{ "resource": "" }
q857
Connection.write_frame
train
def write_frame(self, channel_id, frame_out): """Marshal and write an outgoing pamqp frame to the Socket. :param int channel_id: Channel ID. :param specification.Frame frame_out: Amqp frame. :return: """ frame_data = pamqp_frame.marshal(frame_out, channel_id) self.heartbeat.register_write() self._io.write_to_socket(frame_data)
python
{ "resource": "" }
q858
Connection.write_frames
train
def write_frames(self, channel_id, frames_out): """Marshal and write multiple outgoing pamqp frames to the Socket. :param int channel_id: Channel ID/ :param list frames_out: Amqp frames. :return: """ data_out = EMPTY_BUFFER for single_frame in frames_out: data_out += pamqp_frame.marshal(single_frame, channel_id) self.heartbeat.register_write() self._io.write_to_socket(data_out)
python
{ "resource": "" }
q859
Connection._close_remaining_channels
train
def _close_remaining_channels(self): """Forcefully close all open channels. :return: """ for channel_id in list(self._channels): self._channels[channel_id].set_state(Channel.CLOSED) self._channels[channel_id].close() self._cleanup_channel(channel_id)
python
{ "resource": "" }
q860
Connection._handle_amqp_frame
train
def _handle_amqp_frame(self, data_in): """Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame """ if not data_in: return data_in, None, None try: byte_count, channel_id, frame_in = pamqp_frame.unmarshal(data_in) return data_in[byte_count:], channel_id, frame_in except pamqp_exception.UnmarshalingException: pass except specification.AMQPFrameError as why: LOGGER.error('AMQPFrameError: %r', why, exc_info=True) except ValueError as why: LOGGER.error(why, exc_info=True) self.exceptions.append(AMQPConnectionError(why)) return data_in, None, None
python
{ "resource": "" }
q861
Connection._read_buffer
train
def _read_buffer(self, data_in): """Process the socket buffer, and direct the data to the appropriate channel. :rtype: bytes """ while data_in: data_in, channel_id, frame_in = self._handle_amqp_frame(data_in) if frame_in is None: break self.heartbeat.register_read() if channel_id == 0: self._channel0.on_frame(frame_in) elif channel_id in self._channels: self._channels[channel_id].on_frame(frame_in) return data_in
python
{ "resource": "" }
q862
Connection._cleanup_channel
train
def _cleanup_channel(self, channel_id): """Remove the the channel from the list of available channels. :param int channel_id: Channel id :return: """ with self.lock: if channel_id not in self._channels: return del self._channels[channel_id]
python
{ "resource": "" }
q863
Connection._validate_parameters
train
def _validate_parameters(self): """Validate Connection Parameters. :return: """ if not compatibility.is_string(self.parameters['hostname']): raise AMQPInvalidArgument('hostname should be a string') elif not compatibility.is_integer(self.parameters['port']): raise AMQPInvalidArgument('port should be an integer') elif not compatibility.is_string(self.parameters['username']): raise AMQPInvalidArgument('username should be a string') elif not compatibility.is_string(self.parameters['password']): raise AMQPInvalidArgument('password should be a string') elif not compatibility.is_string(self.parameters['virtual_host']): raise AMQPInvalidArgument('virtual_host should be a string') elif not isinstance(self.parameters['timeout'], (int, float)): raise AMQPInvalidArgument('timeout should be an integer or float') elif not compatibility.is_integer(self.parameters['heartbeat']): raise AMQPInvalidArgument('heartbeat should be an integer')
python
{ "resource": "" }
q864
Connection._wait_for_connection_state
train
def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30): """Wait for a Connection state. :param int state: State that we expect :raises AMQPConnectionError: Raises if we are unable to establish a connection to RabbitMQ. :return: """ start_time = time.time() while self.current_state != state: self.check_for_errors() if time.time() - start_time > rpc_timeout: raise AMQPConnectionError('Connection timed out') sleep(IDLE_WAIT)
python
{ "resource": "" }
q865
Consumer.start
train
def start(self): """Start the Consumers. :return: """ if not self.connection: self.create_connection() while True: try: channel = self.connection.channel() channel.queue.declare('simple_queue') channel.basic.consume(self, 'simple_queue', no_ack=False) channel.start_consuming() if not channel.consumer_tags: channel.close() except amqpstorm.AMQPError as why: LOGGER.exception(why) self.create_connection() except KeyboardInterrupt: self.connection.close() break
python
{ "resource": "" }
q866
ScalableConsumer.stop
train
def stop(self): """Stop all consumers. :return: """ while self._consumers: consumer = self._consumers.pop() consumer.stop() self._stopped.set() self._connection.close()
python
{ "resource": "" }
q867
ScalableConsumer._stop_consumers
train
def _stop_consumers(self, number_of_consumers=0): """Stop a specific number of consumers. :param number_of_consumers: :return: """ while len(self._consumers) > number_of_consumers: consumer = self._consumers.pop() consumer.stop()
python
{ "resource": "" }
q868
ScalableConsumer._start_consumer
train
def _start_consumer(self, consumer): """Start a consumer as a new Thread. :param Consumer consumer: :return: """ thread = threading.Thread(target=consumer.start, args=(self._connection,)) thread.daemon = True thread.start()
python
{ "resource": "" }
q869
Tx.select
train
def select(self): """Enable standard transaction mode. This will enable transaction mode on the channel. Meaning that messages will be kept in the remote server buffer until such a time that either commit or rollback is called. :return: """ self._tx_active = True return self._channel.rpc_request(specification.Tx.Select())
python
{ "resource": "" }
q870
Tx.rollback
train
def rollback(self): """Abandon the current transaction. Rollback all messages published during the current transaction session to the remote server. Note that all messages published during this transaction session will be lost, and will have to be published again. A new transaction session starts as soon as the command has been executed. :return: """ self._tx_active = False return self._channel.rpc_request(specification.Tx.Rollback())
python
{ "resource": "" }
q871
rpc_call
train
def rpc_call(payload): """Simple Flask implementation for making asynchronous Rpc calls. """ # Send the request and store the requests Unique ID. corr_id = RPC_CLIENT.send_request(payload) # Wait until we have received a response. while RPC_CLIENT.queue[corr_id] is None: sleep(0.1) # Return the response to the user. return RPC_CLIENT.queue[corr_id]
python
{ "resource": "" }
q872
RpcClient._create_process_thread
train
def _create_process_thread(self): """Create a thread responsible for consuming messages in response to RPC requests. """ thread = threading.Thread(target=self._process_data_events) thread.setDaemon(True) thread.start()
python
{ "resource": "" }
q873
Message.create
train
def create(channel, body, properties=None): """Create a new Message. :param Channel channel: AMQPStorm Channel :param bytes|str|unicode body: Message payload :param dict properties: Message properties :rtype: Message """ properties = properties or {} if 'correlation_id' not in properties: properties['correlation_id'] = str(uuid.uuid4()) if 'message_id' not in properties: properties['message_id'] = str(uuid.uuid4()) if 'timestamp' not in properties: properties['timestamp'] = datetime.utcnow() return Message(channel, auto_decode=False, body=body, properties=properties)
python
{ "resource": "" }
q874
Message.body
train
def body(self): """Return the Message Body. If auto_decode is enabled, the body will automatically be decoded using decode('utf-8') if possible. :rtype: bytes|str|unicode """ if not self._auto_decode: return self._body if 'body' in self._decode_cache: return self._decode_cache['body'] body = try_utf8_decode(self._body) self._decode_cache['body'] = body return body
python
{ "resource": "" }
q875
Message.publish
train
def publish(self, routing_key, exchange='', mandatory=False, immediate=False): """Publish Message. :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None """ return self._channel.basic.publish(body=self._body, routing_key=routing_key, exchange=exchange, properties=self._properties, mandatory=mandatory, immediate=immediate)
python
{ "resource": "" }
q876
Message._update_properties
train
def _update_properties(self, name, value): """Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return: """ if self._auto_decode and 'properties' in self._decode_cache: self._decode_cache['properties'][name] = value self._properties[name] = value
python
{ "resource": "" }
q877
Message._try_decode_utf8_content
train
def _try_decode_utf8_content(self, content, content_type): """Generic function to decode content. :param object content: :return: """ if not self._auto_decode or not content: return content if content_type in self._decode_cache: return self._decode_cache[content_type] if isinstance(content, dict): content = self._try_decode_dict(content) else: content = try_utf8_decode(content) self._decode_cache[content_type] = content return content
python
{ "resource": "" }
q878
Message._try_decode_dict
train
def _try_decode_dict(self, content): """Decode content of a dictionary. :param dict content: :return: """ result = dict() for key, value in content.items(): key = try_utf8_decode(key) if isinstance(value, dict): result[key] = self._try_decode_dict(value) elif isinstance(value, list): result[key] = self._try_decode_list(value) elif isinstance(value, tuple): result[key] = self._try_decode_tuple(value) else: result[key] = try_utf8_decode(value) return result
python
{ "resource": "" }
q879
Message._try_decode_list
train
def _try_decode_list(content): """Decode content of a list. :param list|tuple content: :return: """ result = list() for value in content: result.append(try_utf8_decode(value)) return result
python
{ "resource": "" }
q880
Basic.get
train
def get(self, queue, virtual_host='/', requeue=False, to_dict=False, count=1, truncate=50000, encoding='auto'): """Get Messages. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool requeue: Re-queue message :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param int count: How many messages should we try to fetch. :param int truncate: The maximum length in bytes, beyond that the server will truncate the message. :param str encoding: Message encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ ackmode = 'ack_requeue_false' if requeue: ackmode = 'ack_requeue_true' get_messages = json.dumps( { 'count': count, 'requeue': requeue, 'ackmode': ackmode, 'encoding': encoding, 'truncate': truncate, 'vhost': virtual_host } ) virtual_host = quote(virtual_host, '') response = self.http_client.post(API_BASIC_GET_MESSAGE % ( virtual_host, queue ), payload=get_messages) if to_dict: return response messages = [] for message in response: if 'payload' in message: message['body'] = message.pop('payload') messages.append(Message(channel=None, auto_decode=True, **message)) return messages
python
{ "resource": "" }
q881
VirtualHost.get
train
def get(self, virtual_host): """Get Virtual Host details. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOST % virtual_host)
python
{ "resource": "" }
q882
VirtualHost.create
train
def create(self, virtual_host): """Create a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.put(API_VIRTUAL_HOST % virtual_host)
python
{ "resource": "" }
q883
VirtualHost.delete
train
def delete(self, virtual_host): """Delete a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_VIRTUAL_HOST % virtual_host)
python
{ "resource": "" }
q884
VirtualHost.get_permissions
train
def get_permissions(self, virtual_host): """Get all Virtual hosts permissions. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOSTS_PERMISSION % ( virtual_host ))
python
{ "resource": "" }
q885
BaseChannel.add_consumer_tag
train
def add_consumer_tag(self, tag): """Add a Consumer tag. :param str tag: Consumer tag. :return: """ if not is_string(tag): raise AMQPChannelError('consumer tag needs to be a string') if tag not in self._consumer_tags: self._consumer_tags.append(tag)
python
{ "resource": "" }
q886
BaseChannel.remove_consumer_tag
train
def remove_consumer_tag(self, tag=None): """Remove a Consumer tag. If no tag is specified, all all tags will be removed. :param str|None tag: Consumer tag. :return: """ if tag is not None: if tag in self._consumer_tags: self._consumer_tags.remove(tag) else: self._consumer_tags = []
python
{ "resource": "" }
q887
BaseMessage.to_dict
train
def to_dict(self): """Message to Dictionary. :rtype: dict """ return { 'body': self._body, 'method': self._method, 'properties': self._properties, 'channel': self._channel }
python
{ "resource": "" }
q888
BaseMessage.to_tuple
train
def to_tuple(self): """Message to Tuple. :rtype: tuple """ return self._body, self._channel, self._method, self._properties
python
{ "resource": "" }
q889
Connection.close
train
def close(self, connection, reason='Closed via management api'): """Close Connection. :param str connection: Connection name :param str reason: Reason for closing connection. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ close_payload = json.dumps({ 'name': connection, 'reason': reason }) connection = quote(connection, '') return self.http_client.delete(API_CONNECTION % connection, payload=close_payload, headers={ 'X-Reason': reason })
python
{ "resource": "" }
q890
Rpc.on_frame
train
def on_frame(self, frame_in): """On RPC Frame. :param specification.Frame frame_in: Amqp frame. :return: """ if frame_in.name not in self._request: return False uuid = self._request[frame_in.name] if self._response[uuid]: self._response[uuid].append(frame_in) else: self._response[uuid] = [frame_in] return True
python
{ "resource": "" }
q891
Rpc.register_request
train
def register_request(self, valid_responses): """Register a RPC request. :param list valid_responses: List of possible Responses that we should be waiting for. :return: """ uuid = str(uuid4()) self._response[uuid] = [] for action in valid_responses: self._request[action] = uuid return uuid
python
{ "resource": "" }
q892
Rpc.get_request
train
def get_request(self, uuid, raw=False, multiple=False, connection_adapter=None): """Get a RPC request. :param str uuid: Rpc Identifier :param bool raw: If enabled return the frame as is, else return result as a dictionary. :param bool multiple: Are we expecting multiple frames. :param obj connection_adapter: Provide custom connection adapter. :return: """ if uuid not in self._response: return self._wait_for_request( uuid, connection_adapter or self._default_connection_adapter ) frame = self._get_response_frame(uuid) if not multiple: self.remove(uuid) result = None if raw: result = frame elif frame is not None: result = dict(frame) return result
python
{ "resource": "" }
q893
Rpc._get_response_frame
train
def _get_response_frame(self, uuid): """Get a response frame. :param str uuid: Rpc Identifier :return: """ frame = None frames = self._response.get(uuid, None) if frames: frame = frames.pop(0) return frame
python
{ "resource": "" }
q894
Rpc._wait_for_request
train
def _wait_for_request(self, uuid, connection_adapter=None): """Wait for RPC request to arrive. :param str uuid: Rpc Identifier. :param obj connection_adapter: Provide custom connection adapter. :return: """ start_time = time.time() while not self._response[uuid]: connection_adapter.check_for_errors() if time.time() - start_time > self._timeout: self._raise_rpc_timeout_error(uuid) time.sleep(IDLE_WAIT)
python
{ "resource": "" }
q895
Rpc._raise_rpc_timeout_error
train
def _raise_rpc_timeout_error(self, uuid): """Gather information and raise an Rpc exception. :param str uuid: Rpc Identifier. :return: """ requests = [] for key, value in self._request.items(): if value == uuid: requests.append(key) self.remove(uuid) message = ( 'rpc requests %s (%s) took too long' % ( uuid, ', '.join(requests) ) ) raise AMQPChannelError(message)
python
{ "resource": "" }
q896
get_default_ssl_version
train
def get_default_ssl_version(): """Get the highest support TLS version, if none is available, return None. :rtype: bool|None """ if hasattr(ssl, 'PROTOCOL_TLSv1_2'): return ssl.PROTOCOL_TLSv1_2 elif hasattr(ssl, 'PROTOCOL_TLSv1_1'): return ssl.PROTOCOL_TLSv1_1 elif hasattr(ssl, 'PROTOCOL_TLSv1'): return ssl.PROTOCOL_TLSv1 return None
python
{ "resource": "" }
q897
is_string
train
def is_string(obj): """Is this a string. :param object obj: :rtype: bool """ if PYTHON3: str_type = (bytes, str) else: str_type = (bytes, str, unicode) return isinstance(obj, str_type)
python
{ "resource": "" }
q898
is_integer
train
def is_integer(obj): """Is this an integer. :param object obj: :return: """ if PYTHON3: return isinstance(obj, int) return isinstance(obj, (int, long))
python
{ "resource": "" }
q899
try_utf8_decode
train
def try_utf8_decode(value): """Try to decode an object. :param value: :return: """ if not value or not is_string(value): return value elif PYTHON3 and not isinstance(value, bytes): return value elif not PYTHON3 and not isinstance(value, unicode): return value try: return value.decode('utf-8') except UnicodeDecodeError: pass return value
python
{ "resource": "" }