func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def _try_options(options, exceptions,
jid, metadata, negotiation_timeout, loop, logger):
for host, port, conn in options:
logger.debug(
"domain %s: trying to connect to %r:%s using %r",
jid.domain, host, port, conn
)
try:
transport, x... | Helper function for :func:`connect_xmlstream`. |
def connect_xmlstream(
jid,
metadata,
negotiation_timeout=60.,
override_peer=[],
loop=None,
logger=logger):
loop = asyncio.get_event_loop() if loop is None else loop
options = list(override_peer)
exceptions = []
result = yield from _try_options(
... | Prepare and connect a :class:`aioxmpp.protocol.XMLStream` to a server
responsible for the given `jid` and authenticate against that server using
the SASL mechansims described in `metadata`.
:param jid: Address of the user for which the connection is made.
:type jid: :class:`aioxmpp.JID`
:param meta... |
def start(self):
if self.running:
raise RuntimeError("client already running")
self._main_task = asyncio.ensure_future(
self._main(),
loop=self._loop
)
self._main_task.add_done_callback(self._on_main_done) | Start the client. If it is already :attr:`running`,
:class:`RuntimeError` is raised.
While the client is running, it will try to keep an XMPP connection
open to the server associated with :attr:`local_jid`. |
def stop(self):
if not self.running:
return
self.logger.debug("stopping main task of %r", self, stack_info=True)
self._main_task.cancel() | Stop the client. This sends a signal to the clients main task which
makes it terminate.
It may take some cycles through the event loop to stop the client
task. To check whether the task has actually stopped, query
:attr:`running`. |
def connected(self, *, presence=structs.PresenceState(False), **kwargs):
return UseConnected(self, presence=presence, **kwargs) | Return a :class:`.node.UseConnected` context manager which does not
modify the presence settings.
The keyword arguments are passed to the :class:`.node.UseConnected`
context manager constructor.
.. versionadded:: 0.8 |
def enqueue(self, stanza, **kwargs):
if not self.established_event.is_set():
raise ConnectionError("stream is not ready")
return self.stream._enqueue(stanza, **kwargs) | Put a `stanza` in the internal transmission queue and return a token to
track it.
:param stanza: Stanza to send
:type stanza: :class:`IQ`, :class:`Message` or :class:`Presence`
:param kwargs: see :class:`StanzaToken`
:raises ConnectionError: if the stream is not :attr:`establish... |
def send(self, stanza, *, timeout=None, cb=None):
if not self.running:
raise ConnectionError("client is not running")
if not self.established:
self.logger.debug("send(%s): stream not established, waiting",
stanza)
# wait for the ... | Send a stanza.
:param stanza: Stanza to send
:type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` o... |
def set_presence(self, state, status):
self._presence_server.set_presence(state, status=status) | Set the presence `state` and `status` on the client. This has the same
effects as writing `state` to :attr:`presence`, but the status of the
presence is also set at the same time.
`status` must be either a string or something which can be passed to
:class:`dict`. If it is a string, the ... |
def _add_conversation(self, conversation):
handler = functools.partial(
self._handle_conversation_exit,
conversation
)
tokens = []
def linked_token(signal, handler):
return signal, signal.connect(handler)
tokens.append(linked_token(con... | Add the conversation and fire the :meth:`on_conversation_added` event.
:param conversation: The conversation object to add.
:type conversation: :class:`~.AbstractConversation`
The conversation is added to the internal list of conversations which
can be queried at :attr:`conversations`.... |
def ping(client, peer):
iq = aioxmpp.IQ(
to=peer,
type_=aioxmpp.IQType.GET,
payload=ping_xso.Ping()
)
yield from client.send(iq) | Ping a peer.
:param peer: The peer to ping.
:type peer: :class:`aioxmpp.JID`
:raises aioxmpp.errors.XMPPError: as received
Send a :xep:`199` ping IQ to `peer` and wait for the reply.
This is a low-level version of :meth:`aioxmpp.PingService.ping`.
**When to use this function vs. the service ... |
def register_header(self, name):
self._node.register_feature(
"#".join([namespaces.xep0131_shim, name])
) | Register support for the SHIM header with the given `name`.
If the header has already been registered as supported,
:class:`ValueError` is raised. |
def unregister_header(self, name):
self._node.unregister_feature(
"#".join([namespaces.xep0131_shim, name])
) | Unregister support for the SHIM header with the given `name`.
If the header is currently not registered as supported,
:class:`KeyError` is raised. |
def get_vcard(self, jid=None):
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
to=jid,
payload=vcard_xso.VCard(),
)
try:
return (yield from self.client.send(iq))
except aioxmpp.XMPPCancelError as e:
if e.condition in (
... | Get the vCard stored for the jid `jid`. If `jid` is
:data:`None` get the vCard of the connected entity.
:param jid: the object to retrieve.
:returns: the stored vCard.
We mask a :class:`XMPPCancelError` in case it is
``feature-not-implemented`` or ``item-not-found`` and return
... |
def set_vcard(self, vcard):
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=vcard,
)
yield from self.client.send(iq) | Store the vCard `vcard` for the connected entity.
:param vcard: the vCard to store.
.. note::
`vcard` should always be derived from the result of
`get_vcard` to preserve the elements of the vcard the
client does not modify.
.. warning::
It is in t... |
def handle(self, state, message=False):
if message:
if state != chatstates_xso.ChatState.ACTIVE:
raise ValueError(
"Only the state ACTIVE can be sent with messages."
)
elif self._state == state:
return False
sel... | Handle a state update.
:param state: the new chat state
:type state: :class:`~aioxmpp.chatstates.ChatState`
:param message: pass true to indicate that we handle the
:data:`ACTIVE` state that is implied by
sending a content message.
:type ... |
def make_application_error(name, tag):
cls = type(xso.XSO)(name, (xso.XSO,), {
"TAG": tag,
})
Error.as_application_condition(cls)
return cls | Create and return a **class** inheriting from :class:`.xso.XSO`. The
:attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`.
In addition, the class is automatically registered with
:attr:`.Error.application_condition` using
:meth:`~.Error.as_application_condition`.
Keep in mind th... |
def from_exception(cls, exc):
result = cls(
condition=exc.condition,
type_=exc.TYPE,
text=exc.text
)
result.application_condition = exc.application_defined_condition
return result | Construct a new :class:`Error` payload from the attributes of the
exception.
:param exc: The exception to convert
:type exc: :class:`aioxmpp.errors.XMPPError`
:result: Newly constructed error payload
:rtype: :class:`Error`
.. versionchanged:: 0.10
The :attr... |
def to_exception(self):
if hasattr(self.application_condition, "to_exception"):
result = self.application_condition.to_exception(self.type_)
if isinstance(result, Exception):
return result
return self.EXCEPTION_CLS_MAP[self.type_](
condition=s... | Convert the error payload to a :class:`~aioxmpp.errors.XMPPError`
subclass.
:result: Newly constructed exception
:rtype: :class:`aioxmpp.errors.XMPPError`
The exact type of the result depends on the :attr:`type_` (see
:class:`~aioxmpp.errors.XMPPError` about the existing subcla... |
def autoset_id(self):
try:
self.id_
except AttributeError:
pass
else:
if self.id_:
return
self.id_ = to_nmtoken(random.getrandbits(8*RANDOM_ID_BYTES)) | If the :attr:`id_` already has a non-false (false is also the empty
string!) value, this method is a no-op.
Otherwise, the :attr:`id_` attribute is filled with
:data:`RANDOM_ID_BYTES` of random data, encoded by
:func:`aioxmpp.utils.to_nmtoken`.
.. note::
This method... |
def make_error(self, error):
obj = type(self)(
from_=self.to,
to=self.from_,
# because flat is better than nested (sarcasm)
type_=type(self).type_.type_.enum_class.ERROR,
)
obj.id_ = self.id_
obj.error = error
return obj | Create a new instance of this stanza (this directly uses
``type(self)``, so also works for subclasses without extra care) which
has the given `error` value set as :attr:`error`.
In addition, the :attr:`id_`, :attr:`from_` and :attr:`to` values are
transferred from the original (with fro... |
def make_reply(self):
obj = super()._make_reply(self.type_)
obj.id_ = None
return obj | Create a reply for the message. The :attr:`id_` attribute is cleared in
the reply. The :attr:`from_` and :attr:`to` are swapped and the
:attr:`type_` attribute is the same as the one of the original
message.
The new :class:`Message` object is returned. |
def close(self):
if (self._smachine.state == State.CLOSING or
self._smachine.state == State.CLOSED):
return
self._writer.close()
if self._transport.can_write_eof():
self._transport.write_eof()
if self._smachine.state == State.STREAM_HEADER... | Close the XML stream and the underlying transport.
This gracefully shuts down the XML stream and the transport, if
possible by writing the eof using :meth:`asyncio.Transport.write_eof`
after sending the stream footer.
After a call to :meth:`close`, no other stream manipulating or sendi... |
def reset(self):
self._require_connection(accept_partial=True)
self._reset_state()
self._writer.start()
self._smachine.rewind(State.STREAM_HEADER_SENT) | Reset the stream by discarding all state and re-sending the stream
header.
Calling :meth:`reset` when the stream is disconnected or currently
disconnecting results in either :class:`ConnectionError` being raised
or the exception which caused the stream to die (possibly a received
... |
def abort(self):
if self._smachine.state == State.CLOSED:
return
if self._smachine.state == State.READY:
self._smachine.state = State.CLOSED
return
if (self._smachine.state != State.CLOSING and
self._transport.can_write_eof()):
... | Abort the stream by writing an EOF if possible and closing the
transport.
The transport is closed using :meth:`asyncio.BaseTransport.close`, so
buffered data is sent, but no more data will be received. The stream is
in :attr:`State.CLOSED` state afterwards.
This also works if t... |
def starttls(self, ssl_context, post_handshake_callback=None):
self._require_connection()
if not self.can_starttls():
raise RuntimeError("starttls not available on transport")
yield from self._transport.starttls(ssl_context,
post_h... | Start TLS on the transport and wait for it to complete.
The `ssl_context` and `post_handshake_callback` arguments are forwarded
to the transports
:meth:`aioopenssl.STARTTLSTransport.starttls` coroutine method.
If the transport does not support starttls, :class:`RuntimeError` is
... |
def error_future(self):
fut = asyncio.Future(loop=self._loop)
self._error_futures.append(fut)
return fut | Return a future which will receive the next XML stream error as
exception.
It is safe to cancel the future at any time. |
def get_features(self, jid):
response = yield from self._disco.query_info(jid)
result = set()
for feature in response.features:
try:
result.add(pubsub_xso.Feature(feature))
except ValueError:
continue
return result | Return the features supported by a service.
:param jid: Address of the PubSub service to query.
:type jid: :class:`aioxmpp.JID`
:return: Set of supported features
:rtype: set containing :class:`~.pubsub.xso.Feature` enumeration
members.
This simply uses service ... |
def subscribe(self, jid, node=None, *,
subscription_jid=None,
config=None):
subscription_jid = subscription_jid or self.client.local_jid.bare()
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET)
iq.payload = pubsub_xso.Request(
... | Subscribe to a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to subscribe to.
:type node: :class:`str`
:param subscription_jid: The address to subscribe to the service.
:type subscription_jid: :class... |
def unsubscribe(self, jid, node=None, *,
subscription_jid=None,
subid=None):
subscription_jid = subscription_jid or self.client.local_jid.bare()
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET)
iq.payload = pubsub_xso.Request(
... | Unsubscribe from a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to unsubscribe from.
:type node: :class:`str`
:param subscription_jid: The address to subscribe from the service.
:type subscription_j... |
def get_subscription_config(self, jid, node=None, *,
subscription_jid=None,
subid=None):
subscription_jid = subscription_jid or self.client.local_jid.bare()
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)
i... | Request the current configuration of a subscription.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:param subscription_jid: The address to query the configuration for.
:t... |
def get_default_config(self, jid, node=None):
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)
iq.payload = pubsub_xso.Request(
pubsub_xso.Default(node=node)
)
response = yield from self.client.send(iq)
return response.payload.data | Request the default configuration of a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:raises aioxmpp.errors.XMPPError: as returned by the service
:return: The defau... |
def get_node_config(self, jid, node=None):
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)
iq.payload = pubsub_xso.OwnerRequest(
pubsub_xso.OwnerConfigure(node=node)
)
response = yield from self.client.send(iq)
return response.payload.data | Request the configuration of a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:raises aioxmpp.errors.XMPPError: as returned by the service
:return: The configuration... |
def set_node_config(self, jid, config, node=None):
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET)
iq.payload = pubsub_xso.OwnerRequest(
pubsub_xso.OwnerConfigure(node=node)
)
iq.payload.payload.data = config
yield from self.client.send(iq) | Update the configuration of a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param config: Configuration form
:type config: :class:`aioxmpp.forms.Data`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:rai... |
def get_items(self, jid, node, *, max_items=None):
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)
iq.payload = pubsub_xso.Request(
pubsub_xso.Items(node, max_items=max_items)
)
return (yield from self.client.send(iq)) | Request the most recent items from a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:param max_items: Number of items to return at most.
:type max_items: :class:`int... |
def get_items_by_id(self, jid, node, ids):
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)
iq.payload = pubsub_xso.Request(
pubsub_xso.Items(node)
)
iq.payload.payload.items = [
pubsub_xso.Item(id_)
for id_ in ids
]
... | Request specific items by their IDs from a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:param ids: The item IDs to return.
:type ids: :class:`~collections.abc.Ite... |
def get_subscriptions(self, jid, node=None):
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)
iq.payload = pubsub_xso.Request(
pubsub_xso.Subscriptions(node=node)
)
response = yield from self.client.send(iq)
return response.payload | Return all subscriptions of the local entity to a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:raises aioxmpp.errors.XMPPError: as returned by the service
:return... |
def publish(self, jid, node, payload, *,
id_=None,
publish_options=None):
publish = pubsub_xso.Publish()
publish.node = node
if payload is not None:
item = pubsub_xso.Item()
item.id_ = id_
item.registered_payload = payl... | Publish an item to a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to publish to.
:type node: :class:`str`
:param payload: Registered payload to publish.
:type payload: :class:`aioxmpp.xso.XSO`
... |
def retract(self, jid, node, id_, *, notify=False):
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)
... | 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:`... |
def create(self, jid, node=None):
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)
... | 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 n... |
def delete(self, jid, node, *, redirect_uri=None):
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=jid,
payload=pubsub_xso.OwnerRequest(
pubsub_xso.OwnerDelete(
node,
redirect_uri=redirect_uri
... | 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 fo... |
def get_nodes(self, jid, node=None):
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,
... | 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
... |
def get_node_affiliations(self, jid, node):
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)) | 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 ... |
def change_node_affiliations(self, jid, node, affiliations_to_set):
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=jid,
payload=pubsub_xso.OwnerRequest(
pubsub_xso.OwnerAffiliations(
node,
affiliat... | 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: :cla... |
def change_node_subscriptions(self, jid, node, subscriptions_to_set):
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=jid,
payload=pubsub_xso.OwnerRequest(
pubsub_xso.OwnerSubscriptions(
node,
subsc... | 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: ... |
def purge(self, jid, node):
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=jid,
payload=pubsub_xso.OwnerRequest(
pubsub_xso.OwnerPurge(
node
)
)
)
yield from self.client.sen... | 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`. |
def capture_events(receiver, dest):
# the following code is a copy of the formal definition of `yield from`
# in PEP 380, with modifications to capture the value sent during yield
_i = iter(receiver)
try:
_y = next(_i)
except StopIteration as _e:
return _e.value
try:
... | Capture all events sent to `receiver` in the sequence `dest`. This is a
generator, and it is best used with ``yield from``. The observable effect
of using this generator with ``yield from`` is identical to the effect of
using `receiver` with ``yield from`` directly (including the return value),
but in a... |
def events_to_sax(events, dest):
name_stack = []
for ev_type, *ev_args in events:
if ev_type == "start":
name = (ev_args[0], ev_args[1])
dest.startElementNS(name, None, ev_args[2])
name_stack.append(name)
elif ev_type == "end":
name = name_sta... | Convert an iterable `events` of XSO events to SAX events by calling the
matching SAX methods on `dest` |
def filter(self, *, type_=None, lang=None, attrs={}):
result = self
if type_ is not None:
result = self._filter_type(result, type_)
if lang is not None:
result = self._filter_lang(result, lang)
if attrs:
result = self._filter_attrs(result, att... | Return an iterable which produces a sequence of the elements inside
this :class:`XSOList`, filtered by the criteria given as arguments. The
function starts with a working sequence consisting of the whole list.
If `type_` is not :data:`None`, elements which are not an instance of
the giv... |
def filtered(self, *, type_=None, lang=None, attrs={}):
return list(self.filter(type_=type_, lang=lang, attrs=attrs)) | This method is a convencience wrapper around :meth:`filter` which
evaluates the result into a list and returns that list. |
def from_value(self, instance, value):
try:
parsed = self.type_.parse(value)
except (TypeError, ValueError):
if self.erroneous_as_absent:
return False
raise
self._set_from_recv(instance, parsed)
return True | Convert the given value using the set `type_` and store it into
`instance`’ attribute. |
def to_sax(self, instance, dest):
value = self.__get__(instance, type(instance))
if value is None:
return
dest.characters(self.type_.format(value)) | Assign the formatted value stored at `instance`’ attribute to the text
of `el`.
If the `value` is :data:`None`, no text is generated. |
def from_events(self, instance, ev_args, ctx):
obj = yield from self._process(instance, ev_args, ctx)
self.__set__(instance, obj)
return obj | 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. |
def to_sax(self, instance, dest):
obj = self.__get__(instance, type(instance))
if obj is None:
return
obj.unparse_to_sax(dest) | Take the object associated with this descriptor on `instance` and
serialize it as child into the given :class:`lxml.etree.Element`
`parent`.
If the object is :data:`None`, no content is generated. |
def from_events(self, instance, ev_args, ctx):
obj = yield from self._process(instance, ev_args, ctx)
self.__get__(instance, type(instance)).append(obj)
return obj | Like :meth:`.Child.from_events`, but instead of replacing the attribute
value, the new object is appended to the list. |
def from_events(self, instance, ev_args, ctx):
# goal: collect all elements starting with the element for which we got
# the start-ev_args in a lxml.etree.Element.
def make_from_args(ev_args, parent):
el = etree.SubElement(parent,
tag_to_str... | Collect the events and convert them to a single XML subtree, which then
gets appended to the list at `instance`. `ev_args` must be the
arguments of the ``"start"`` event of the new child.
This method is suspendable. |
def handle_missing(self, instance, ctx):
if self.missing is not None:
value = self.missing(instance, ctx)
if value is not None:
self._set_from_code(instance, value)
return
if self.default is _PropBase.NO_DEFAULT:
raise ValueErr... | Handle a missing attribute on `instance`. This is called whenever no
value for the attribute is found during parsing. The call to
:meth:`missing` is independent of the value of `required`.
If the `missing` callback is not :data:`None`, it is called with the
`instance` and the `ctx` as a... |
def to_dict(self, instance, d):
value = self.__get__(instance, type(instance))
if value == self.default:
return
d[self.tag] = self.type_.format(value) | Override the implementation from :class:`Text` by storing the formatted
value in the XML attribute instead of the character data.
If the value is :data:`None`, no element is generated. |
def from_events(self, instance, ev_args, ctx):
# goal: take all text inside the child element and collect it as
# attribute value
attrs = ev_args[2]
if attrs and self.attr_policy == UnknownAttrPolicy.FAIL:
raise ValueError("unexpected attribute (at text only node)")
... | Starting with the element to which the start event information in
`ev_args` belongs, parse text data. If any children are encountered,
:attr:`child_policy` is enforced (see
:class:`UnknownChildPolicy`). Likewise, if the start event contains
attributes, :attr:`attr_policy` is enforced
... |
def to_sax(self, instance, dest):
value = self.__get__(instance, type(instance))
if value == self.default:
return
if self.declare_prefix is not False and self.tag[0]:
dest.startPrefixMapping(self.declare_prefix, self.tag[0])
dest.startElementNS(self.tag, ... | Create a child node at `parent` with the tag :attr:`tag`. Set the text
contents to the value of the attribute which this descriptor represents
at `instance`.
If the value is :data:`None`, no element is generated. |
def fill_into_dict(self, items, dest):
for item in items:
dest[self.key(item)].append(item) | Take an iterable of `items` and group it into the given `dest` dict,
using the :attr:`key` function.
The `dest` dict must either already contain the keys which are
generated by the :attr:`key` function for the items in `items`, or must
default them suitably. The values of the affected k... |
def from_events(self, instance, ev_args, ctx):
tag = ev_args[0], ev_args[1]
cls = self._tag_map[tag]
obj = yield from cls.parse_events(ev_args, ctx)
mapping = self.__get__(instance, type(instance))
mapping[self.key(obj)].append(obj) | Like :meth:`.ChildList.from_events`, but the object is appended to the
list associated with its tag in the dict. |
def parse_events(cls, ev_args, parent_ctx):
with parent_ctx as ctx:
obj = cls.__new__(cls)
attrs = ev_args[2]
attr_map = cls.ATTR_MAP.copy()
for key, value in attrs.items():
try:
prop = attr_map.pop(key)
... | Create an instance of this class, using the events sent into this
function. `ev_args` must be the event arguments of the ``"start"``
event.
.. seealso::
You probably should not call this method directly, but instead use
:class:`XSOParser` with a :class:`SAXDriver`.
... |
def register_child(cls, prop, child_cls):
if cls.__subclasses__():
raise TypeError(
"register_child is forbidden on classes with subclasses"
" (subclasses: {})".format(
", ".join(map(str, cls.__subclasses__()))
))
i... | Register a new :class:`XMLStreamClass` instance `child_cls` for a given
:class:`Child` descriptor `prop`.
.. warning::
This method cannot be used after a class has been derived from this
class. This is for consistency: the method modifies the bookkeeping
attributes of ... |
def parse_events(cls, ev_args, parent_ctx):
dest = [("start", )+tuple(ev_args)]
result = yield from capture_events(
super().parse_events(ev_args, parent_ctx),
dest
)
result._set_captured_events(dest)
return result | Capture the events sent to :meth:`.XSO.parse_events`,
including the initial `ev_args` to a list and call
:meth:`_set_captured_events` on the result of
:meth:`.XSO.parse_events`.
Like the method it overrides, :meth:`parse_events` is suspendable. |
def add_class(self, cls, callback):
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[c... | 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. |
def remove_class(self, cls):
del self._tag_map[cls.TAG]
del self._class_map[cls] | Remove a XSO class `cls` from parsing. This method raises
:class:`KeyError` with the classes :attr:`TAG` attribute as argument if
removing fails because the class is not registered. |
def check_against_tables(chars, tables):
for c in chars:
if any(in_table(c) for in_table in tables):
return c
return None | Perform a check against the table predicates in `tables`. `tables` must be
a reusable iterable containing characteristic functions of character sets,
that is, functions which return :data:`True` if the character is in the
table.
The function returns the first character occuring in any of the tables or
... |
def check_bidi(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... | Check proper bidirectionality as per stringprep. Operates on a list of
unicode characters provided in `chars`. |
def check_prohibited_output(chars, bad_tables):
violator = check_against_tables(chars, bad_tables)
if violator is not None:
raise ValueError("Input contains invalid unicode codepoint: "
"U+{:04x}".format(ord(violator))) | 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`. |
def check_unassigned(chars, bad_tables):
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))) | 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`. |
def nodeprep(string, allow_unassigned=False):
chars = list(string)
_nodeprep_do_mapping(chars)
do_normalization(chars)
check_prohibited_output(
chars,
(
stringprep.in_table_c11,
stringprep.in_table_c12,
stringprep.in_table_c21,
stringp... | Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised. |
def resourceprep(string, allow_unassigned=False):
chars = list(string)
_resourceprep_do_mapping(chars)
do_normalization(chars)
check_prohibited_output(
chars,
(
stringprep.in_table_c12,
stringprep.in_table_c21,
stringprep.in_table_c22,
... | Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised. |
def add_avatar_image(self, mime_type, *, id_=None,
image_bytes=None, width=None, height=None,
url=None, nbytes=None):
if mime_type == "image/png":
if image_bytes is not None:
if self._image_bytes is not 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 da... |
def get_avatar_metadata(self, jid, *, require_fresh=False,
disable_pep=False):
if require_fresh:
self._metadata_cache.pop(jid, None)
else:
try:
return self._metadata_cache[jid]
except KeyError:
pass
... | 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_... |
def publish_avatar_set(self, avatar_set):
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_x... | 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... |
def disable_avatar(self):
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(
n... | 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 avat... |
def wipe_avatar(self):
@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,
... | 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 avatar... |
def block_jids(self, jids_to_block):
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.cl... | Add the JIDs in the sequence `jids_to_block` to the client's
blocklist. |
def unblock_jids(self, jids_to_unblock):
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 fr... | Remove the JIDs in the sequence `jids_to_block` from the
client's blocklist. |
def _register_descriptor_keys(self, descriptor, keys):
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_d... | 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
:ra... |
def from_xso(self, xso):
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
... | 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`` mismatche... |
def render_reply(self):
data = copy.copy(self._recv_xso)
data.type_ = forms_xso.DataType.SUBMIT
data.fields = list(self._recv_xso.fields)
for i, field_xso in enumerate(data.fields):
if field_xso.var is None:
continue
if field_xso.var == "F... | Create a :class:`~.Data` object equal to the object from which the from
was created through :meth:`from_xso`, except that the values of the
fields are exchanged with the values set on the form.
Fields which have no corresponding form descriptor are left untouched.
Fields which are acces... |
def render_request(self):
data = forms_xso.Data(type_=forms_xso.DataType.FORM)
try:
layout = self.LAYOUT
except AttributeError:
layout = list(self.DESCRIPTORS)
my_form_type = getattr(self, "FORM_TYPE", None)
if my_form_type is not None:
... | Create a :class:`Data` object containing all fields known to the
:class:`Form`. If the :class:`Form` has a :attr:`LAYOUT` attribute, it
is used during generation. |
def lookup(self, key):
try:
result = self.lookup_in_database(key)
except KeyError:
pass
else:
return result
while True:
fut = self._lookup_cache[key]
try:
result = yield from fut
except Value... | Look up the given `node` URL using the given `hash_` first in the
database and then by waiting on the futures created with
:meth:`create_query_future` for that node URL and hash.
If the hash is not in the database, :meth:`lookup` iterates as long as
there are pending futures for the giv... |
def create_query_future(self, key):
fut = asyncio.Future()
fut.add_done_callback(
functools.partial(self._erase_future, key)
)
self._lookup_cache[key] = fut
return fut | Create and return a :class:`asyncio.Future` for the given `hash_`
function and `node` URL. The future is referenced internally and used
by any calls to :meth:`lookup` which are made while the future is
pending. The future is removed from the internal storage automatically
when a result o... |
def add_cache_entry(self, key, entry):
copied_entry = copy.copy(entry)
self._memory_overlay[key] = copied_entry
if self._user_db_path is not None:
asyncio.ensure_future(asyncio.get_event_loop().run_in_executor(
None,
writeback,
... | Add the given `entry` (which must be a :class:`~.disco.xso.InfoQuery`
instance) to the user-level database keyed with the hash function type
`hash_` and the `node` URL. The `entry` is **not** validated to
actually map to `node` with the given `hash_` function, it is expected
that the cal... |
def claim_pep_node(self, node_namespace, *,
register_feature=True, notify=False):
if node_namespace in self._pep_node_claims:
raise RuntimeError(
"claiming already claimed node"
)
registered_node = RegisteredPEPNode(
sel... | 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 ... |
def available(self):
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 | Check whether we have a PEP identity associated with our account. |
def publish(self, node, data, *, id_=None, access_model=None):
publish_options = None
def autocreate_publish_options():
nonlocal publish_options
if publish_options is None:
publish_options = aioxmpp.forms.Data(
aioxmpp.forms.DataType.S... | 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.
... |
def close(self):
if self._closed:
return
self._closed = True
self._pep_service._unclaim(self.node_namespace)
self._unregister() | 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`. |
def full_clean(self, exclude, validate_unique=False):
# 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 Valida... | 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: |
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email]) | Send an email to this User. |
def activate_users(self, request, queryset):
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':... | Activates the selected users, if they are not already
activated. |
def send_activation_email(self, request, queryset):
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, _('Activati... | Send activation emails for the selected users, if they are not already
activated. |
def get_queryset(self):
try:
qs = super(UserManager, self).get_queryset()
except AttributeError: # pragma: no cover
qs = super(UserManager, self).get_query_set()
return qs | Fixes get_query_set vs get_queryset for Django <1.6 |
def is_ready(self):
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(AM... | Is Socket Ready.
:rtype: tuple |
def close(self):
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'])
... | Close Socket.
:return: |
def open(self):
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)
sel... | Open Socket and establish a connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: |
def write_to_socket(self, frame_data):
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 s... | Write data to the socket.
:param str frame_data:
:return: |
def _close_socket(self):
try:
self.socket.shutdown(socket.SHUT_RDWR)
except (OSError, socket.error):
pass
self.socket.close() | Shutdown and close the Socket.
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.