id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
800 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.retract | 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 | 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)
iq.payload = pubsub_xso.Request(
retract
)
yield from self.client.send(iq) | [
"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",
")",
"iq",
".",
"payload",
"=",
"pubsub_xso",
".",
"Request",
"(",
"retract",
")",
"yield",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | 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",
"a",
"previously",
"published",
"item",
"from",
"a",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L749-L782 |
801 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.create | 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 | 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)
if response is not None and response.payload.node is not None:
return response.payload.node
return node | [
"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",
")",
"if",
"response",
"is",
"not",
"None",
"and",
"response",
".",
"payload",
".",
"node",
"is",
"not",
"None",
":",
"return",
"response",
".",
"payload",
".",
"node",
"return",
"node"
] | 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",
"a",
"new",
"node",
"at",
"a",
"service",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L785-L817 |
802 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.delete | 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 | 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
)
)
)
yield from self.client.send(iq) | [
"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",
")",
")",
")",
"yield",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | 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. | [
"Delete",
"an",
"existing",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L820-L849 |
803 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.get_nodes | 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 | 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,
item.name,
))
return result | [
"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",
",",
"item",
".",
"name",
",",
")",
")",
"return",
"result"
] | 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. | [
"Request",
"all",
"nodes",
"at",
"a",
"service",
"or",
"collection",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L852-L891 |
804 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.get_node_affiliations | 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 | 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)) | [
"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 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. | [
"Return",
"the",
"affiliations",
"of",
"other",
"jids",
"at",
"a",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L894-L918 |
805 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.change_node_affiliations | 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 | 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,
affiliations=[
pubsub_xso.OwnerAffiliation(
jid,
affiliation
)
for jid, affiliation in affiliations_to_set
]
)
)
)
yield from self.client.send(iq) | [
"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",
",",
"affiliations",
"=",
"[",
"pubsub_xso",
".",
"OwnerAffiliation",
"(",
"jid",
",",
"affiliation",
")",
"for",
"jid",
",",
"affiliation",
"in",
"affiliations_to_set",
"]",
")",
")",
")",
"yield",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | 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. | [
"Update",
"the",
"affiliations",
"at",
"a",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L948-L982 |
806 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.change_node_subscriptions | 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 | 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,
subscriptions=[
pubsub_xso.OwnerSubscription(
jid,
subscription
)
for jid, subscription in subscriptions_to_set
]
)
)
)
yield from self.client.send(iq) | [
"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",
",",
"subscriptions",
"=",
"[",
"pubsub_xso",
".",
"OwnerSubscription",
"(",
"jid",
",",
"subscription",
")",
"for",
"jid",
",",
"subscription",
"in",
"subscriptions_to_set",
"]",
")",
")",
")",
"yield",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | 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. | [
"Update",
"the",
"subscriptions",
"at",
"a",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L985-L1020 |
807 | horazont/aioxmpp | aioxmpp/pubsub/service.py | PubSubClient.purge | 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 | 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.send(iq) | [
"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",
".",
"send",
"(",
"iq",
")"
] | 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`. | [
"Delete",
"all",
"items",
"from",
"a",
"node",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L1023-L1044 |
808 | horazont/aioxmpp | aioxmpp/xso/model.py | Child.from_events | 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 | def from_events(self, instance, ev_args, ctx):
obj = yield from self._process(instance, ev_args, ctx)
self.__set__(instance, obj)
return obj | [
"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. | [
"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",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L556-L566 |
809 | horazont/aioxmpp | aioxmpp/xso/model.py | XSOParser.add_class | 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 | 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[cls.TAG] = (cls, callback) | [
"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",
"[",
"cls",
".",
"TAG",
"]",
"=",
"(",
"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. | [
"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",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2496-L2508 |
810 | horazont/aioxmpp | aioxmpp/stringprep.py | check_bidi | 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 | 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:
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.") | [
"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",
":",
"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.\"",
")"
] | Check proper bidirectionality as per stringprep. Operates on a list of
unicode characters provided in `chars`. | [
"Check",
"proper",
"bidirectionality",
"as",
"per",
"stringprep",
".",
"Operates",
"on",
"a",
"list",
"of",
"unicode",
"characters",
"provided",
"in",
"chars",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L81-L104 |
811 | horazont/aioxmpp | aioxmpp/stringprep.py | check_prohibited_output | 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 | 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))) | [
"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`. | [
"Check",
"against",
"prohibited",
"output",
"by",
"checking",
"whether",
"any",
"of",
"the",
"characters",
"from",
"chars",
"are",
"in",
"any",
"of",
"the",
"bad_tables",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L107-L117 |
812 | horazont/aioxmpp | aioxmpp/stringprep.py | check_unassigned | 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 | 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))) | [
"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`. | [
"Check",
"that",
"chars",
"does",
"not",
"contain",
"any",
"unassigned",
"code",
"points",
"as",
"per",
"the",
"given",
"list",
"of",
"bad_tables",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L120-L133 |
813 | horazont/aioxmpp | aioxmpp/avatar/service.py | AvatarSet.add_avatar_image | 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 | 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:
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
)
) | [
"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",
":",
"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",
")",
")"
] | 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. | [
"Add",
"a",
"source",
"of",
"the",
"avatar",
"image",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L95-L183 |
814 | horazont/aioxmpp | aioxmpp/avatar/service.py | AvatarService.get_avatar_metadata | 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 | 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
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] | [
"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",
"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",
"]"
] | 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. | [
"Retrieve",
"a",
"list",
"of",
"avatar",
"descriptors",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L835-L896 |
815 | horazont/aioxmpp | aioxmpp/avatar/service.py | AvatarService.publish_avatar_set | 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 | 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_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"
) | [
"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_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\"",
")"
] | 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. | [
"Make",
"avatar_set",
"the",
"current",
"avatar",
"of",
"the",
"jid",
"associated",
"with",
"this",
"connection",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L913-L956 |
816 | horazont/aioxmpp | aioxmpp/avatar/service.py | AvatarService.disable_avatar | 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 | 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(
namespaces.xep0084_metadata,
avatar_xso.Metadata()
))
yield from gather_reraise_multi(*todo, message="disable_avatar") | [
"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",
"(",
"namespaces",
".",
"xep0084_metadata",
",",
"avatar_xso",
".",
"Metadata",
"(",
")",
")",
")",
"yield",
"from",
"gather_reraise_multi",
"(",
"*",
"todo",
",",
"message",
"=",
"\"disable_avatar\"",
")"
] | 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. | [
"Temporarily",
"disable",
"the",
"avatar",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L967-L995 |
817 | horazont/aioxmpp | aioxmpp/avatar/service.py | AvatarService.wipe_avatar | 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 | 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,
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") | [
"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",
",",
"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\"",
")"
] | 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. | [
"Remove",
"all",
"avatar",
"data",
"stored",
"on",
"the",
"server",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L998-L1034 |
818 | horazont/aioxmpp | aioxmpp/blocking/service.py | BlockingClient.block_jids | 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 | 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.client.send(iq) | [
"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",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | Add the JIDs in the sequence `jids_to_block` to the client's
blocklist. | [
"Add",
"the",
"JIDs",
"in",
"the",
"sequence",
"jids_to_block",
"to",
"the",
"client",
"s",
"blocklist",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/blocking/service.py#L134-L149 |
819 | horazont/aioxmpp | aioxmpp/blocking/service.py | BlockingClient.unblock_jids | 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 | 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 from self.client.send(iq) | [
"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",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | Remove the JIDs in the sequence `jids_to_block` from the
client's blocklist. | [
"Remove",
"the",
"JIDs",
"in",
"the",
"sequence",
"jids_to_block",
"from",
"the",
"client",
"s",
"blocklist",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/blocking/service.py#L152-L167 |
820 | horazont/aioxmpp | aioxmpp/forms/form.py | DescriptorClass._register_descriptor_keys | 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 | 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_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 | [
"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_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"
] | 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. | [
"Register",
"the",
"given",
"descriptor",
"keys",
"for",
"the",
"given",
"descriptor",
"at",
"the",
"class",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/form.py#L177-L227 |
821 | horazont/aioxmpp | aioxmpp/forms/form.py | FormClass.from_xso | 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 | 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
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 | [
"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",
"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"
] | 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. | [
"Construct",
"and",
"return",
"an",
"instance",
"from",
"the",
"given",
"xso",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/form.py#L231-L307 |
822 | horazont/aioxmpp | aioxmpp/pep/service.py | PEPClient.claim_pep_node | 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 | 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(
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 | [
"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",
"(",
"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"
] | 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. | [
"Claim",
"node",
"node_namespace",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L90-L146 |
823 | horazont/aioxmpp | aioxmpp/pep/service.py | PEPClient.available | 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 | 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 | [
"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. | [
"Check",
"whether",
"we",
"have",
"a",
"PEP",
"identity",
"associated",
"with",
"our",
"account",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L152-L163 |
824 | horazont/aioxmpp | aioxmpp/pep/service.py | PEPClient.publish | 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 | 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.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
)) | [
"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",
".",
"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",
")",
")"
] | 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",
"an",
"item",
"data",
"in",
"the",
"PubSub",
"node",
"node",
"on",
"the",
"PEP",
"service",
"associated",
"with",
"the",
"user",
"s",
"JID",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L193-L249 |
825 | horazont/aioxmpp | aioxmpp/pep/service.py | RegisteredPEPNode.close | 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 | def close(self):
if self._closed:
return
self._closed = True
self._pep_service._unclaim(self.node_namespace)
self._unregister() | [
"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`. | [
"Unclaim",
"the",
"PEP",
"node",
"and",
"unregister",
"the",
"registered",
"features",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L326-L338 |
826 | neo4j-contrib/django-neomodel | django_neomodel/__init__.py | DjangoNode.full_clean | 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 | 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 ValidationError({e.property_name: 'is required'}) | [
"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",
"ValidationError",
"(",
"{",
"e",
".",
"property_name",
":",
"'is required'",
"}",
")"
] | 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",
"node",
"on",
"error",
"raising",
"ValidationErrors",
"which",
"can",
"be",
"handled",
"by",
"django",
"forms"
] | 9bee6708c0df8e4d1b546fe57e1f735e63a29d81 | https://github.com/neo4j-contrib/django-neomodel/blob/9bee6708c0df8e4d1b546fe57e1f735e63a29d81/django_neomodel/__init__.py#L148-L163 |
827 | mishbahr/django-users2 | users/models.py | AbstractUser.email_user | def email_user(self, subject, message, from_email=None):
""" Send an email to this User."""
send_mail(subject, message, from_email, [self.email]) | python | def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email]) | [
"def",
"email_user",
"(",
"self",
",",
"subject",
",",
"message",
",",
"from_email",
"=",
"None",
")",
":",
"send_mail",
"(",
"subject",
",",
"message",
",",
"from_email",
",",
"[",
"self",
".",
"email",
"]",
")"
] | Send an email to this User. | [
"Send",
"an",
"email",
"to",
"this",
"User",
"."
] | 1ee244dc4ca162b2331d2a44d45848fdcb80f329 | https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/models.py#L47-L49 |
828 | mishbahr/django-users2 | users/admin.py | UserAdmin.activate_users | 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 | 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': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS) | [
"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'",
":",
"n",
",",
"'items'",
":",
"model_ngettext",
"(",
"self",
".",
"opts",
",",
"n",
")",
"}",
",",
"messages",
".",
"SUCCESS",
")"
] | Activates the selected users, if they are not already
activated. | [
"Activates",
"the",
"selected",
"users",
"if",
"they",
"are",
"not",
"already",
"activated",
"."
] | 1ee244dc4ca162b2331d2a44d45848fdcb80f329 | https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/admin.py#L79-L93 |
829 | mishbahr/django-users2 | users/admin.py | UserAdmin.send_activation_email | 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 | 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, _('Activation emails sent to %(count)d %(items)s.') %
{'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS) | [
"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",
",",
"_",
"(",
"'Activation emails sent to %(count)d %(items)s.'",
")",
"%",
"{",
"'count'",
":",
"n",
",",
"'items'",
":",
"model_ngettext",
"(",
"self",
".",
"opts",
",",
"n",
")",
"}",
",",
"messages",
".",
"SUCCESS",
")"
] | Send activation emails for the selected users, if they are not already
activated. | [
"Send",
"activation",
"emails",
"for",
"the",
"selected",
"users",
"if",
"they",
"are",
"not",
"already",
"activated",
"."
] | 1ee244dc4ca162b2331d2a44d45848fdcb80f329 | https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/admin.py#L96-L109 |
830 | mishbahr/django-users2 | users/managers.py | UserManager.get_queryset | 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 | 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 | [
"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 | [
"Fixes",
"get_query_set",
"vs",
"get_queryset",
"for",
"Django",
"<1",
".",
"6"
] | 1ee244dc4ca162b2331d2a44d45848fdcb80f329 | https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/managers.py#L11-L19 |
831 | eandersson/amqpstorm | amqpstorm/io.py | Poller.is_ready | 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 | 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(AMQPConnectionError(why))
return False | [
"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",
"(",
"AMQPConnectionError",
"(",
"why",
")",
")",
"return",
"False"
] | Is Socket Ready.
:rtype: tuple | [
"Is",
"Socket",
"Ready",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L39-L51 |
832 | eandersson/amqpstorm | amqpstorm/io.py | IO.close | 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 | 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'])
self._inbound_thread = None
self.poller = None
self.socket = None
finally:
self._wr_lock.release()
self._rd_lock.release() | [
"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'",
"]",
")",
"self",
".",
"_inbound_thread",
"=",
"None",
"self",
".",
"poller",
"=",
"None",
"self",
".",
"socket",
"=",
"None",
"finally",
":",
"self",
".",
"_wr_lock",
".",
"release",
"(",
")",
"self",
".",
"_rd_lock",
".",
"release",
"(",
")"
] | Close Socket.
:return: | [
"Close",
"Socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L70-L88 |
833 | eandersson/amqpstorm | amqpstorm/io.py | IO.open | 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 | 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)
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() | [
"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",
")",
"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",
"(",
")"
] | Open Socket and establish a connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | [
"Open",
"Socket",
"and",
"establish",
"a",
"connection",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L90-L109 |
834 | eandersson/amqpstorm | amqpstorm/io.py | IO.write_to_socket | 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 | 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 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() | [
"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",
"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",
"(",
")"
] | Write data to the socket.
:param str frame_data:
:return: | [
"Write",
"data",
"to",
"the",
"socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L111-L139 |
835 | eandersson/amqpstorm | amqpstorm/io.py | IO._close_socket | 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 | def _close_socket(self):
try:
self.socket.shutdown(socket.SHUT_RDWR)
except (OSError, socket.error):
pass
self.socket.close() | [
"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: | [
"Shutdown",
"and",
"close",
"the",
"Socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L141-L150 |
836 | eandersson/amqpstorm | amqpstorm/io.py | IO._get_socket_addresses | 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 | def _get_socket_addresses(self):
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 | [
"def",
"_get_socket_addresses",
"(",
"self",
")",
":",
"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"
] | Get Socket address information.
:rtype: list | [
"Get",
"Socket",
"address",
"information",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L152-L166 |
837 | eandersson/amqpstorm | amqpstorm/io.py | IO._find_address_and_connect | 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 | def _find_address_and_connect(self, addresses):
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
)
) | [
"def",
"_find_address_and_connect",
"(",
"self",
",",
"addresses",
")",
":",
"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",
")",
")"
] | Find and connect to the appropriate address.
:param addresses:
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: socket.socket | [
"Find",
"and",
"connect",
"to",
"the",
"appropriate",
"address",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L168-L192 |
838 | eandersson/amqpstorm | amqpstorm/io.py | IO._create_socket | 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 | def _create_socket(self, socket_family):
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 | [
"def",
"_create_socket",
"(",
"self",
",",
"socket_family",
")",
":",
"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"
] | Create Socket.
:param int socket_family:
:rtype: socket.socket | [
"Create",
"Socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L194-L208 |
839 | eandersson/amqpstorm | amqpstorm/io.py | IO._ssl_wrap_socket | 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 | def _ssl_wrap_socket(self, sock):
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']
) | [
"def",
"_ssl_wrap_socket",
"(",
"self",
",",
"sock",
")",
":",
"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'",
"]",
")"
] | Wrap SSLSocket around the Socket.
:param socket.socket sock:
:rtype: SSLSocket | [
"Wrap",
"SSLSocket",
"around",
"the",
"Socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L210-L230 |
840 | eandersson/amqpstorm | amqpstorm/io.py | IO._create_inbound_thread | 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 | def _create_inbound_thread(self):
inbound_thread = threading.Thread(target=self._process_incoming_data,
name=__name__)
inbound_thread.daemon = True
inbound_thread.start()
return inbound_thread | [
"def",
"_create_inbound_thread",
"(",
"self",
")",
":",
"inbound_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_process_incoming_data",
",",
"name",
"=",
"__name__",
")",
"inbound_thread",
".",
"daemon",
"=",
"True",
"inbound_thread",
".",
"start",
"(",
")",
"return",
"inbound_thread"
] | Internal Thread that handles all incoming traffic.
:rtype: threading.Thread | [
"Internal",
"Thread",
"that",
"handles",
"all",
"incoming",
"traffic",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L232-L241 |
841 | eandersson/amqpstorm | amqpstorm/io.py | IO._process_incoming_data | 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 | def _process_incoming_data(self):
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) | [
"def",
"_process_incoming_data",
"(",
"self",
")",
":",
"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",
")"
] | Retrieve and process any incoming data.
:return: | [
"Retrieve",
"and",
"process",
"any",
"incoming",
"data",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L243-L251 |
842 | eandersson/amqpstorm | amqpstorm/io.py | IO._receive | 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 | def _receive(self):
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 | [
"def",
"_receive",
"(",
"self",
")",
":",
"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"
] | Receive any incoming socket data.
If an error is thrown, handle it and return an empty string.
:return: data_in
:rtype: bytes | [
"Receive",
"any",
"incoming",
"socket",
"data",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L253-L270 |
843 | eandersson/amqpstorm | amqpstorm/io.py | IO._read_from_socket | 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 | def _read_from_socket(self):
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) | [
"def",
"_read_from_socket",
"(",
"self",
")",
":",
"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",
")"
] | Read data from the socket.
:rtype: bytes | [
"Read",
"data",
"from",
"the",
"socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L272-L285 |
844 | eandersson/amqpstorm | amqpstorm/heartbeat.py | Heartbeat.start | 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 | def start(self, exceptions):
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() | [
"def",
"start",
"(",
"self",
",",
"exceptions",
")",
":",
"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",
"(",
")"
] | Start the Heartbeat Checker.
:param list exceptions:
:return: | [
"Start",
"the",
"Heartbeat",
"Checker",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L40-L55 |
845 | eandersson/amqpstorm | amqpstorm/heartbeat.py | Heartbeat.stop | def stop(self):
"""Stop the Heartbeat Checker.
:return:
"""
self._running.clear()
with self._lock:
if self._timer:
self._timer.cancel()
self._timer = None | python | def stop(self):
self._running.clear()
with self._lock:
if self._timer:
self._timer.cancel()
self._timer = None | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_running",
".",
"clear",
"(",
")",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_timer",
":",
"self",
".",
"_timer",
".",
"cancel",
"(",
")",
"self",
".",
"_timer",
"=",
"None"
] | Stop the Heartbeat Checker.
:return: | [
"Stop",
"the",
"Heartbeat",
"Checker",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L57-L66 |
846 | eandersson/amqpstorm | amqpstorm/heartbeat.py | Heartbeat._check_for_life_signs | 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 | def _check_for_life_signs(self):
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() | [
"def",
"_check_for_life_signs",
"(",
"self",
")",
":",
"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",
"(",
")"
] | 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 | [
"Check",
"Connection",
"for",
"life",
"signs",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L68-L99 |
847 | eandersson/amqpstorm | amqpstorm/heartbeat.py | Heartbeat._raise_or_append_exception | 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 | def _raise_or_append_exception(self):
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) | [
"def",
"_raise_or_append_exception",
"(",
"self",
")",
":",
"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",
")"
] | 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: | [
"The",
"connection",
"is",
"presumably",
"dead",
"and",
"we",
"need",
"to",
"raise",
"or",
"append",
"an",
"exception",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L101-L119 |
848 | eandersson/amqpstorm | amqpstorm/heartbeat.py | Heartbeat._start_new_timer | 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 | def _start_new_timer(self):
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 | [
"def",
"_start_new_timer",
"(",
"self",
")",
":",
"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"
] | Create a timer that will be used to periodically check the
connection for heartbeats.
:return: | [
"Create",
"a",
"timer",
"that",
"will",
"be",
"used",
"to",
"periodically",
"check",
"the",
"connection",
"for",
"heartbeats",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L121-L135 |
849 | eandersson/amqpstorm | amqpstorm/management/queue.py | Queue.get | 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 | def get(self, queue, virtual_host='/'):
virtual_host = quote(virtual_host, '')
return self.http_client.get(
API_QUEUE % (
virtual_host,
queue
)
) | [
"def",
"get",
"(",
"self",
",",
"queue",
",",
"virtual_host",
"=",
"'/'",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"API_QUEUE",
"%",
"(",
"virtual_host",
",",
"queue",
")",
")"
] | 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 | [
"Get",
"Queue",
"details",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L15-L32 |
850 | eandersson/amqpstorm | amqpstorm/management/queue.py | Queue.list | 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 | def list(self, virtual_host='/', show_all=False):
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
) | [
"def",
"list",
"(",
"self",
",",
"virtual_host",
"=",
"'/'",
",",
"show_all",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"List",
"Queues",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L34-L50 |
851 | eandersson/amqpstorm | amqpstorm/management/queue.py | Queue.bindings | 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 | def bindings(self, queue, virtual_host='/'):
virtual_host = quote(virtual_host, '')
return self.http_client.get(API_QUEUE_BINDINGS %
(
virtual_host,
queue
)) | [
"def",
"bindings",
"(",
"self",
",",
"queue",
",",
"virtual_host",
"=",
"'/'",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"API_QUEUE_BINDINGS",
"%",
"(",
"virtual_host",
",",
"queue",
")",
")"
] | 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 | [
"Get",
"Queue",
"bindings",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L122-L138 |
852 | eandersson/amqpstorm | amqpstorm/management/exchange.py | Exchange.get | 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 | def get(self, exchange, virtual_host='/'):
virtual_host = quote(virtual_host, '')
return self.http_client.get(
API_EXCHANGE
% (
virtual_host,
exchange)
) | [
"def",
"get",
"(",
"self",
",",
"exchange",
",",
"virtual_host",
"=",
"'/'",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"API_EXCHANGE",
"%",
"(",
"virtual_host",
",",
"exchange",
")",
")"
] | 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 | [
"Get",
"Exchange",
"details",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L14-L31 |
853 | eandersson/amqpstorm | amqpstorm/management/exchange.py | Exchange.list | 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 | def list(self, virtual_host='/', show_all=False):
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
) | [
"def",
"list",
"(",
"self",
",",
"virtual_host",
"=",
"'/'",
",",
"show_all",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"List",
"Exchanges",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L33-L49 |
854 | eandersson/amqpstorm | amqpstorm/management/exchange.py | Exchange.bindings | 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 | def bindings(self, exchange, virtual_host='/'):
virtual_host = quote(virtual_host, '')
return self.http_client.get(API_EXCHANGE_BINDINGS %
(
virtual_host,
exchange
)) | [
"def",
"bindings",
"(",
"self",
",",
"exchange",
",",
"virtual_host",
"=",
"'/'",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"API_EXCHANGE_BINDINGS",
"%",
"(",
"virtual_host",
",",
"exchange",
")",
")"
] | 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 | [
"Get",
"Exchange",
"bindings",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L107-L123 |
855 | eandersson/amqpstorm | amqpstorm/connection.py | Connection.check_for_errors | 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 | def check_for_errors(self):
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] | [
"def",
"check_for_errors",
"(",
"self",
")",
":",
"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",
"]"
] | Check Connection for errors.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | [
"Check",
"Connection",
"for",
"errors",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L172-L186 |
856 | eandersson/amqpstorm | amqpstorm/connection.py | Connection.open | 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 | def open(self):
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') | [
"def",
"open",
"(",
"self",
")",
":",
"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'",
")"
] | Open Connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error. | [
"Open",
"Connection",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L211-L226 |
857 | eandersson/amqpstorm | amqpstorm/connection.py | Connection.write_frame | 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 | def write_frame(self, channel_id, frame_out):
frame_data = pamqp_frame.marshal(frame_out, channel_id)
self.heartbeat.register_write()
self._io.write_to_socket(frame_data) | [
"def",
"write_frame",
"(",
"self",
",",
"channel_id",
",",
"frame_out",
")",
":",
"frame_data",
"=",
"pamqp_frame",
".",
"marshal",
"(",
"frame_out",
",",
"channel_id",
")",
"self",
".",
"heartbeat",
".",
"register_write",
"(",
")",
"self",
".",
"_io",
".",
"write_to_socket",
"(",
"frame_data",
")"
] | Marshal and write an outgoing pamqp frame to the Socket.
:param int channel_id: Channel ID.
:param specification.Frame frame_out: Amqp frame.
:return: | [
"Marshal",
"and",
"write",
"an",
"outgoing",
"pamqp",
"frame",
"to",
"the",
"Socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L228-L238 |
858 | eandersson/amqpstorm | amqpstorm/connection.py | Connection.write_frames | 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 | def write_frames(self, channel_id, frames_out):
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) | [
"def",
"write_frames",
"(",
"self",
",",
"channel_id",
",",
"frames_out",
")",
":",
"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",
")"
] | Marshal and write multiple outgoing pamqp frames to the Socket.
:param int channel_id: Channel ID/
:param list frames_out: Amqp frames.
:return: | [
"Marshal",
"and",
"write",
"multiple",
"outgoing",
"pamqp",
"frames",
"to",
"the",
"Socket",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L240-L252 |
859 | eandersson/amqpstorm | amqpstorm/connection.py | Connection._close_remaining_channels | 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 | def _close_remaining_channels(self):
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) | [
"def",
"_close_remaining_channels",
"(",
"self",
")",
":",
"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",
")"
] | Forcefully close all open channels.
:return: | [
"Forcefully",
"close",
"all",
"open",
"channels",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L254-L262 |
860 | eandersson/amqpstorm | amqpstorm/connection.py | Connection._handle_amqp_frame | 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 | def _handle_amqp_frame(self, data_in):
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 | [
"def",
"_handle_amqp_frame",
"(",
"self",
",",
"data_in",
")",
":",
"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"
] | Unmarshal a single AMQP frame and return the result.
:param data_in: socket data
:return: data_in, channel_id, frame | [
"Unmarshal",
"a",
"single",
"AMQP",
"frame",
"and",
"return",
"the",
"result",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L284-L303 |
861 | eandersson/amqpstorm | amqpstorm/connection.py | Connection._read_buffer | 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 | def _read_buffer(self, data_in):
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 | [
"def",
"_read_buffer",
"(",
"self",
",",
"data_in",
")",
":",
"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"
] | Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes | [
"Process",
"the",
"socket",
"buffer",
"and",
"direct",
"the",
"data",
"to",
"the",
"appropriate",
"channel",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L305-L323 |
862 | eandersson/amqpstorm | amqpstorm/connection.py | Connection._cleanup_channel | 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 | def _cleanup_channel(self, channel_id):
with self.lock:
if channel_id not in self._channels:
return
del self._channels[channel_id] | [
"def",
"_cleanup_channel",
"(",
"self",
",",
"channel_id",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"channel_id",
"not",
"in",
"self",
".",
"_channels",
":",
"return",
"del",
"self",
".",
"_channels",
"[",
"channel_id",
"]"
] | Remove the the channel from the list of available channels.
:param int channel_id: Channel id
:return: | [
"Remove",
"the",
"the",
"channel",
"from",
"the",
"list",
"of",
"available",
"channels",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L325-L335 |
863 | eandersson/amqpstorm | amqpstorm/connection.py | Connection._validate_parameters | 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 | def _validate_parameters(self):
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') | [
"def",
"_validate_parameters",
"(",
"self",
")",
":",
"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'",
")"
] | Validate Connection Parameters.
:return: | [
"Validate",
"Connection",
"Parameters",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L344-L362 |
864 | eandersson/amqpstorm | amqpstorm/connection.py | Connection._wait_for_connection_state | 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 | def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30):
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) | [
"def",
"_wait_for_connection_state",
"(",
"self",
",",
"state",
"=",
"Stateful",
".",
"OPEN",
",",
"rpc_timeout",
"=",
"30",
")",
":",
"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",
")"
] | 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: | [
"Wait",
"for",
"a",
"Connection",
"state",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L364-L379 |
865 | eandersson/amqpstorm | examples/robust_consumer.py | Consumer.start | 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 | def start(self):
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 | [
"def",
"start",
"(",
"self",
")",
":",
"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"
] | Start the Consumers.
:return: | [
"Start",
"the",
"Consumers",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/robust_consumer.py#L39-L59 |
866 | eandersson/amqpstorm | examples/scalable_consumer.py | ScalableConsumer.stop | def stop(self):
"""Stop all consumers.
:return:
"""
while self._consumers:
consumer = self._consumers.pop()
consumer.stop()
self._stopped.set()
self._connection.close() | python | def stop(self):
while self._consumers:
consumer = self._consumers.pop()
consumer.stop()
self._stopped.set()
self._connection.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"while",
"self",
".",
"_consumers",
":",
"consumer",
"=",
"self",
".",
"_consumers",
".",
"pop",
"(",
")",
"consumer",
".",
"stop",
"(",
")",
"self",
".",
"_stopped",
".",
"set",
"(",
")",
"self",
".",
"_connection",
".",
"close",
"(",
")"
] | Stop all consumers.
:return: | [
"Stop",
"all",
"consumers",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L69-L78 |
867 | eandersson/amqpstorm | examples/scalable_consumer.py | ScalableConsumer._stop_consumers | 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 | def _stop_consumers(self, number_of_consumers=0):
while len(self._consumers) > number_of_consumers:
consumer = self._consumers.pop()
consumer.stop() | [
"def",
"_stop_consumers",
"(",
"self",
",",
"number_of_consumers",
"=",
"0",
")",
":",
"while",
"len",
"(",
"self",
".",
"_consumers",
")",
">",
"number_of_consumers",
":",
"consumer",
"=",
"self",
".",
"_consumers",
".",
"pop",
"(",
")",
"consumer",
".",
"stop",
"(",
")"
] | Stop a specific number of consumers.
:param number_of_consumers:
:return: | [
"Stop",
"a",
"specific",
"number",
"of",
"consumers",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L131-L139 |
868 | eandersson/amqpstorm | examples/scalable_consumer.py | ScalableConsumer._start_consumer | 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 | def _start_consumer(self, consumer):
thread = threading.Thread(target=consumer.start,
args=(self._connection,))
thread.daemon = True
thread.start() | [
"def",
"_start_consumer",
"(",
"self",
",",
"consumer",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"consumer",
".",
"start",
",",
"args",
"=",
"(",
"self",
".",
"_connection",
",",
")",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")"
] | Start a consumer as a new Thread.
:param Consumer consumer:
:return: | [
"Start",
"a",
"consumer",
"as",
"a",
"new",
"Thread",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L141-L150 |
869 | eandersson/amqpstorm | amqpstorm/tx.py | Tx.select | 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 | def select(self):
self._tx_active = True
return self._channel.rpc_request(specification.Tx.Select()) | [
"def",
"select",
"(",
"self",
")",
":",
"self",
".",
"_tx_active",
"=",
"True",
"return",
"self",
".",
"_channel",
".",
"rpc_request",
"(",
"specification",
".",
"Tx",
".",
"Select",
"(",
")",
")"
] | 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: | [
"Enable",
"standard",
"transaction",
"mode",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/tx.py#L41-L51 |
870 | eandersson/amqpstorm | amqpstorm/tx.py | Tx.rollback | 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 | def rollback(self):
self._tx_active = False
return self._channel.rpc_request(specification.Tx.Rollback()) | [
"def",
"rollback",
"(",
"self",
")",
":",
"self",
".",
"_tx_active",
"=",
"False",
"return",
"self",
".",
"_channel",
".",
"rpc_request",
"(",
"specification",
".",
"Tx",
".",
"Rollback",
"(",
")",
")"
] | 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: | [
"Abandon",
"the",
"current",
"transaction",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/tx.py#L67-L82 |
871 | eandersson/amqpstorm | examples/flask_threaded_rpc_client.py | rpc_call | 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 | def rpc_call(payload):
# 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] | [
"def",
"rpc_call",
"(",
"payload",
")",
":",
"# 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",
"]"
] | Simple Flask implementation for making asynchronous Rpc calls. | [
"Simple",
"Flask",
"implementation",
"for",
"making",
"asynchronous",
"Rpc",
"calls",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/flask_threaded_rpc_client.py#L73-L84 |
872 | eandersson/amqpstorm | examples/flask_threaded_rpc_client.py | RpcClient._create_process_thread | 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 | def _create_process_thread(self):
thread = threading.Thread(target=self._process_data_events)
thread.setDaemon(True)
thread.start() | [
"def",
"_create_process_thread",
"(",
"self",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_process_data_events",
")",
"thread",
".",
"setDaemon",
"(",
"True",
")",
"thread",
".",
"start",
"(",
")"
] | Create a thread responsible for consuming messages in response
to RPC requests. | [
"Create",
"a",
"thread",
"responsible",
"for",
"consuming",
"messages",
"in",
"response",
"to",
"RPC",
"requests",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/flask_threaded_rpc_client.py#L38-L44 |
873 | eandersson/amqpstorm | amqpstorm/message.py | Message.create | 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 | def create(channel, body, properties=None):
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) | [
"def",
"create",
"(",
"channel",
",",
"body",
",",
"properties",
"=",
"None",
")",
":",
"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",
")"
] | Create a new Message.
:param Channel channel: AMQPStorm Channel
:param bytes|str|unicode body: Message payload
:param dict properties: Message properties
:rtype: Message | [
"Create",
"a",
"new",
"Message",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L32-L50 |
874 | eandersson/amqpstorm | amqpstorm/message.py | Message.body | 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 | def body(self):
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 | [
"def",
"body",
"(",
"self",
")",
":",
"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"
] | 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 | [
"Return",
"the",
"Message",
"Body",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L53-L67 |
875 | eandersson/amqpstorm | amqpstorm/message.py | Message.publish | 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 | def publish(self, routing_key, exchange='', mandatory=False,
immediate=False):
return self._channel.basic.publish(body=self._body,
routing_key=routing_key,
exchange=exchange,
properties=self._properties,
mandatory=mandatory,
immediate=immediate) | [
"def",
"publish",
"(",
"self",
",",
"routing_key",
",",
"exchange",
"=",
"''",
",",
"mandatory",
"=",
"False",
",",
"immediate",
"=",
"False",
")",
":",
"return",
"self",
".",
"_channel",
".",
"basic",
".",
"publish",
"(",
"body",
"=",
"self",
".",
"_body",
",",
"routing_key",
"=",
"routing_key",
",",
"exchange",
"=",
"exchange",
",",
"properties",
"=",
"self",
".",
"_properties",
",",
"mandatory",
"=",
"mandatory",
",",
"immediate",
"=",
"immediate",
")"
] | 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 | [
"Publish",
"Message",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L149-L170 |
876 | eandersson/amqpstorm | amqpstorm/message.py | Message._update_properties | 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 | def _update_properties(self, name, value):
if self._auto_decode and 'properties' in self._decode_cache:
self._decode_cache['properties'][name] = value
self._properties[name] = value | [
"def",
"_update_properties",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"self",
".",
"_auto_decode",
"and",
"'properties'",
"in",
"self",
".",
"_decode_cache",
":",
"self",
".",
"_decode_cache",
"[",
"'properties'",
"]",
"[",
"name",
"]",
"=",
"value",
"self",
".",
"_properties",
"[",
"name",
"]",
"=",
"value"
] | Update properties, and keep cache up-to-date if auto decode is
enabled.
:param str name: Key
:param obj value: Value
:return: | [
"Update",
"properties",
"and",
"keep",
"cache",
"up",
"-",
"to",
"-",
"date",
"if",
"auto",
"decode",
"is",
"enabled",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L344-L354 |
877 | eandersson/amqpstorm | amqpstorm/message.py | Message._try_decode_utf8_content | 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 | def _try_decode_utf8_content(self, content, content_type):
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 | [
"def",
"_try_decode_utf8_content",
"(",
"self",
",",
"content",
",",
"content_type",
")",
":",
"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"
] | Generic function to decode content.
:param object content:
:return: | [
"Generic",
"function",
"to",
"decode",
"content",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L356-L371 |
878 | eandersson/amqpstorm | amqpstorm/message.py | Message._try_decode_dict | 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 | def _try_decode_dict(self, content):
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 | [
"def",
"_try_decode_dict",
"(",
"self",
",",
"content",
")",
":",
"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"
] | Decode content of a dictionary.
:param dict content:
:return: | [
"Decode",
"content",
"of",
"a",
"dictionary",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L373-L390 |
879 | eandersson/amqpstorm | amqpstorm/message.py | Message._try_decode_list | 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 | def _try_decode_list(content):
result = list()
for value in content:
result.append(try_utf8_decode(value))
return result | [
"def",
"_try_decode_list",
"(",
"content",
")",
":",
"result",
"=",
"list",
"(",
")",
"for",
"value",
"in",
"content",
":",
"result",
".",
"append",
"(",
"try_utf8_decode",
"(",
"value",
")",
")",
"return",
"result"
] | Decode content of a list.
:param list|tuple content:
:return: | [
"Decode",
"content",
"of",
"a",
"list",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L393-L402 |
880 | eandersson/amqpstorm | amqpstorm/management/basic.py | Basic.get | 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 | def get(self, queue, virtual_host='/', requeue=False, to_dict=False,
count=1, truncate=50000, encoding='auto'):
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 | [
"def",
"get",
"(",
"self",
",",
"queue",
",",
"virtual_host",
"=",
"'/'",
",",
"requeue",
"=",
"False",
",",
"to_dict",
"=",
"False",
",",
"count",
"=",
"1",
",",
"truncate",
"=",
"50000",
",",
"encoding",
"=",
"'auto'",
")",
":",
"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"
] | 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 | [
"Get",
"Messages",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/basic.py#L45-L92 |
881 | eandersson/amqpstorm | amqpstorm/management/virtual_host.py | VirtualHost.get | 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 | def get(self, virtual_host):
virtual_host = quote(virtual_host, '')
return self.http_client.get(API_VIRTUAL_HOST % virtual_host) | [
"def",
"get",
"(",
"self",
",",
"virtual_host",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"API_VIRTUAL_HOST",
"%",
"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 | [
"Get",
"Virtual",
"Host",
"details",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L10-L21 |
882 | eandersson/amqpstorm | amqpstorm/management/virtual_host.py | VirtualHost.create | 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 | def create(self, virtual_host):
virtual_host = quote(virtual_host, '')
return self.http_client.put(API_VIRTUAL_HOST % virtual_host) | [
"def",
"create",
"(",
"self",
",",
"virtual_host",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"put",
"(",
"API_VIRTUAL_HOST",
"%",
"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 | [
"Create",
"a",
"Virtual",
"Host",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L33-L44 |
883 | eandersson/amqpstorm | amqpstorm/management/virtual_host.py | VirtualHost.delete | 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 | def delete(self, virtual_host):
virtual_host = quote(virtual_host, '')
return self.http_client.delete(API_VIRTUAL_HOST % virtual_host) | [
"def",
"delete",
"(",
"self",
",",
"virtual_host",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"delete",
"(",
"API_VIRTUAL_HOST",
"%",
"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 | [
"Delete",
"a",
"Virtual",
"Host",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L46-L57 |
884 | eandersson/amqpstorm | amqpstorm/management/virtual_host.py | VirtualHost.get_permissions | 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 | def get_permissions(self, virtual_host):
virtual_host = quote(virtual_host, '')
return self.http_client.get(API_VIRTUAL_HOSTS_PERMISSION %
(
virtual_host
)) | [
"def",
"get_permissions",
"(",
"self",
",",
"virtual_host",
")",
":",
"virtual_host",
"=",
"quote",
"(",
"virtual_host",
",",
"''",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"API_VIRTUAL_HOSTS_PERMISSION",
"%",
"(",
"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 | [
"Get",
"all",
"Virtual",
"hosts",
"permissions",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L59-L71 |
885 | eandersson/amqpstorm | amqpstorm/base.py | BaseChannel.add_consumer_tag | 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 | def add_consumer_tag(self, tag):
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) | [
"def",
"add_consumer_tag",
"(",
"self",
",",
"tag",
")",
":",
"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",
")"
] | Add a Consumer tag.
:param str tag: Consumer tag.
:return: | [
"Add",
"a",
"Consumer",
"tag",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L123-L132 |
886 | eandersson/amqpstorm | amqpstorm/base.py | BaseChannel.remove_consumer_tag | 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 | def remove_consumer_tag(self, tag=None):
if tag is not None:
if tag in self._consumer_tags:
self._consumer_tags.remove(tag)
else:
self._consumer_tags = [] | [
"def",
"remove_consumer_tag",
"(",
"self",
",",
"tag",
"=",
"None",
")",
":",
"if",
"tag",
"is",
"not",
"None",
":",
"if",
"tag",
"in",
"self",
".",
"_consumer_tags",
":",
"self",
".",
"_consumer_tags",
".",
"remove",
"(",
"tag",
")",
"else",
":",
"self",
".",
"_consumer_tags",
"=",
"[",
"]"
] | Remove a Consumer tag.
If no tag is specified, all all tags will be removed.
:param str|None tag: Consumer tag.
:return: | [
"Remove",
"a",
"Consumer",
"tag",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L134-L146 |
887 | eandersson/amqpstorm | amqpstorm/base.py | BaseMessage.to_dict | def to_dict(self):
"""Message to Dictionary.
:rtype: dict
"""
return {
'body': self._body,
'method': self._method,
'properties': self._properties,
'channel': self._channel
} | python | def to_dict(self):
return {
'body': self._body,
'method': self._method,
'properties': self._properties,
'channel': self._channel
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'body'",
":",
"self",
".",
"_body",
",",
"'method'",
":",
"self",
".",
"_method",
",",
"'properties'",
":",
"self",
".",
"_properties",
",",
"'channel'",
":",
"self",
".",
"_channel",
"}"
] | Message to Dictionary.
:rtype: dict | [
"Message",
"to",
"Dictionary",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L171-L181 |
888 | eandersson/amqpstorm | amqpstorm/base.py | BaseMessage.to_tuple | def to_tuple(self):
"""Message to Tuple.
:rtype: tuple
"""
return self._body, self._channel, self._method, self._properties | python | def to_tuple(self):
return self._body, self._channel, self._method, self._properties | [
"def",
"to_tuple",
"(",
"self",
")",
":",
"return",
"self",
".",
"_body",
",",
"self",
".",
"_channel",
",",
"self",
".",
"_method",
",",
"self",
".",
"_properties"
] | Message to Tuple.
:rtype: tuple | [
"Message",
"to",
"Tuple",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L183-L188 |
889 | eandersson/amqpstorm | amqpstorm/management/connection.py | Connection.close | 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 | def close(self, connection, reason='Closed via management api'):
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
}) | [
"def",
"close",
"(",
"self",
",",
"connection",
",",
"reason",
"=",
"'Closed via management api'",
")",
":",
"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",
"}",
")"
] | 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",
"Connection",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/connection.py#L32-L52 |
890 | eandersson/amqpstorm | amqpstorm/rpc.py | Rpc.on_frame | 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 | def on_frame(self, frame_in):
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 | [
"def",
"on_frame",
"(",
"self",
",",
"frame_in",
")",
":",
"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"
] | On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return: | [
"On",
"RPC",
"Frame",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L29-L43 |
891 | eandersson/amqpstorm | amqpstorm/rpc.py | Rpc.register_request | 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 | def register_request(self, valid_responses):
uuid = str(uuid4())
self._response[uuid] = []
for action in valid_responses:
self._request[action] = uuid
return uuid | [
"def",
"register_request",
"(",
"self",
",",
"valid_responses",
")",
":",
"uuid",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"self",
".",
"_response",
"[",
"uuid",
"]",
"=",
"[",
"]",
"for",
"action",
"in",
"valid_responses",
":",
"self",
".",
"_request",
"[",
"action",
"]",
"=",
"uuid",
"return",
"uuid"
] | Register a RPC request.
:param list valid_responses: List of possible Responses that
we should be waiting for.
:return: | [
"Register",
"a",
"RPC",
"request",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L45-L56 |
892 | eandersson/amqpstorm | amqpstorm/rpc.py | Rpc.get_request | 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 | def get_request(self, uuid, raw=False, multiple=False,
connection_adapter=None):
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 | [
"def",
"get_request",
"(",
"self",
",",
"uuid",
",",
"raw",
"=",
"False",
",",
"multiple",
"=",
"False",
",",
"connection_adapter",
"=",
"None",
")",
":",
"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"
] | 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: | [
"Get",
"a",
"RPC",
"request",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L86-L110 |
893 | eandersson/amqpstorm | amqpstorm/rpc.py | Rpc._get_response_frame | 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 | def _get_response_frame(self, uuid):
frame = None
frames = self._response.get(uuid, None)
if frames:
frame = frames.pop(0)
return frame | [
"def",
"_get_response_frame",
"(",
"self",
",",
"uuid",
")",
":",
"frame",
"=",
"None",
"frames",
"=",
"self",
".",
"_response",
".",
"get",
"(",
"uuid",
",",
"None",
")",
"if",
"frames",
":",
"frame",
"=",
"frames",
".",
"pop",
"(",
"0",
")",
"return",
"frame"
] | Get a response frame.
:param str uuid: Rpc Identifier
:return: | [
"Get",
"a",
"response",
"frame",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L112-L122 |
894 | eandersson/amqpstorm | amqpstorm/rpc.py | Rpc._wait_for_request | 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 | def _wait_for_request(self, uuid, connection_adapter=None):
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) | [
"def",
"_wait_for_request",
"(",
"self",
",",
"uuid",
",",
"connection_adapter",
"=",
"None",
")",
":",
"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",
")"
] | Wait for RPC request to arrive.
:param str uuid: Rpc Identifier.
:param obj connection_adapter: Provide custom connection adapter.
:return: | [
"Wait",
"for",
"RPC",
"request",
"to",
"arrive",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L124-L136 |
895 | eandersson/amqpstorm | amqpstorm/rpc.py | Rpc._raise_rpc_timeout_error | 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 | def _raise_rpc_timeout_error(self, uuid):
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) | [
"def",
"_raise_rpc_timeout_error",
"(",
"self",
",",
"uuid",
")",
":",
"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",
")"
] | Gather information and raise an Rpc exception.
:param str uuid: Rpc Identifier.
:return: | [
"Gather",
"information",
"and",
"raise",
"an",
"Rpc",
"exception",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L138-L156 |
896 | eandersson/amqpstorm | amqpstorm/compatibility.py | get_default_ssl_version | 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 | def get_default_ssl_version():
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 | [
"def",
"get_default_ssl_version",
"(",
")",
":",
"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"
] | Get the highest support TLS version, if none is available, return None.
:rtype: bool|None | [
"Get",
"the",
"highest",
"support",
"TLS",
"version",
"if",
"none",
"is",
"available",
"return",
"None",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L44-L55 |
897 | eandersson/amqpstorm | amqpstorm/compatibility.py | is_string | 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 | def is_string(obj):
if PYTHON3:
str_type = (bytes, str)
else:
str_type = (bytes, str, unicode)
return isinstance(obj, str_type) | [
"def",
"is_string",
"(",
"obj",
")",
":",
"if",
"PYTHON3",
":",
"str_type",
"=",
"(",
"bytes",
",",
"str",
")",
"else",
":",
"str_type",
"=",
"(",
"bytes",
",",
"str",
",",
"unicode",
")",
"return",
"isinstance",
"(",
"obj",
",",
"str_type",
")"
] | Is this a string.
:param object obj:
:rtype: bool | [
"Is",
"this",
"a",
"string",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L74-L84 |
898 | eandersson/amqpstorm | amqpstorm/compatibility.py | is_integer | def is_integer(obj):
"""Is this an integer.
:param object obj:
:return:
"""
if PYTHON3:
return isinstance(obj, int)
return isinstance(obj, (int, long)) | python | def is_integer(obj):
if PYTHON3:
return isinstance(obj, int)
return isinstance(obj, (int, long)) | [
"def",
"is_integer",
"(",
"obj",
")",
":",
"if",
"PYTHON3",
":",
"return",
"isinstance",
"(",
"obj",
",",
"int",
")",
"return",
"isinstance",
"(",
"obj",
",",
"(",
"int",
",",
"long",
")",
")"
] | Is this an integer.
:param object obj:
:return: | [
"Is",
"this",
"an",
"integer",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L87-L95 |
899 | eandersson/amqpstorm | amqpstorm/compatibility.py | try_utf8_decode | 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 | def try_utf8_decode(value):
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 | [
"def",
"try_utf8_decode",
"(",
"value",
")",
":",
"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"
] | Try to decode an object.
:param value:
:return: | [
"Try",
"to",
"decode",
"an",
"object",
"."
] | 38330906c0af19eea482f43c5ce79bab98a1e064 | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L111-L129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.