code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
data = {'amount': amount, 'address': address, 'currency': currency}
response = self._post("ripple_withdrawal/", data=data,
return_json=True)
return self._expect_true(response)
|
def ripple_withdrawal(self, amount, address, currency)
|
Returns true if successful.
| 4.035717
| 3.751539
| 1.07575
|
data = {'amount': amount, 'address': address}
if destination_tag:
data['destination_tag'] = destination_tag
return self._post("xrp_withdrawal/", data=data, return_json=True,
version=2)["id"]
|
def xrp_withdrawal(self, amount, address, destination_tag=None)
|
Sends xrps to another xrp wallet specified by address. Returns withdrawal id.
| 3.654756
| 3.318579
| 1.101301
|
data = {'amount': amount,
'currency': currency,}
if subaccount is not None:
data['subAccount'] = subaccount
return self._post("transfer-to-main/", data=data, return_json=True,
version=2)
|
def transfer_to_main(self, amount, currency, subaccount=None)
|
Returns dictionary with status.
subaccount has to be the numerical id of the subaccount, not the name
| 3.546571
| 3.331179
| 1.064659
|
y_hat = librosa.core.resample(self.y, self.sr, target_sr)
return Sound(y_hat, target_sr)
|
def resample(self, target_sr)
|
Returns a new sound with a samplerate of target_sr.
| 3.360728
| 2.93383
| 1.145509
|
from IPython.display import Audio
return Audio(data=self.y, rate=self.sr)
|
def as_ipywidget(self)
|
Provides an IPywidgets player that can be used in a notebook.
| 6.684381
| 5.147866
| 1.298476
|
y, sr = librosa.load(filename, sr=sr)
return cls(y, sr)
|
def from_file(cls, filename, sr=22050)
|
Loads an audiofile, uses sr=22050 by default.
| 2.380264
| 2.269118
| 1.048982
|
if not hasattr(self, '_it'):
class ChunkIterator(object):
def __iter__(iter):
return iter
def __next__(iter):
try:
chunk = self._next_chunk()
except StopIteration:
if self.loop:
self._init_stretching()
return iter.__next__()
raise
return chunk
next = __next__
self._it = ChunkIterator()
return self._it
|
def chunks(self)
|
Returns a chunk iterator over the sound.
| 3.989844
| 3.522602
| 1.132641
|
freq = numpy.fft.rfft(chunk)
N = len(freq)
shifted_freq = numpy.zeros(N, freq.dtype)
S = numpy.round(shift if shift > 0 else N + shift, 0)
s = N - S
shifted_freq[:S] = freq[s:]
shifted_freq[S:] = freq[:s]
shifted_chunk = numpy.fft.irfft(shifted_freq)
return shifted_chunk.astype(chunk.dtype)
|
def pitch_shifter(self, chunk, shift)
|
Pitch-Shift the given chunk by shift semi-tones.
| 2.904742
| 2.914004
| 0.996821
|
start = self._i2
end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H))
if start >= end:
raise StopIteration
# The not so clean code below basically implements a phase vocoder
out = numpy.zeros(self._N, dtype=numpy.complex)
while self._i2 < end:
if self._i1 + self._N + self._H > len(self.y):
raise StopIteration
a, b = self._i1, self._i1 + self._N
S1 = numpy.fft.fft(self._win * self.y[a: b])
S2 = numpy.fft.fft(self._win * self.y[a + self._H: b + self._H])
self._phi += (numpy.angle(S2) - numpy.angle(S1))
self._phi = self._phi - 2.0 * numpy.pi * numpy.round(self._phi / (2.0 * numpy.pi))
out.real, out.imag = numpy.cos(self._phi), numpy.sin(self._phi)
self._sy[self._i2: self._i2 + self._N] += self._win * numpy.fft.ifft(numpy.abs(S2) * out).real
self._i1 += int(self._H * self.stretch_factor)
self._i2 += self._H
chunk = self._sy[start:end]
if stretch_factor == 1.0:
chunk = self.y[start:end]
return chunk
|
def _time_stretcher(self, stretch_factor)
|
Real time time-scale without pitch modification.
:param int i: index of the beginning of the chunk to stretch
:param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down)
.. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk.
| 3.181824
| 3.134835
| 1.014989
|
(MID, END, CONT, LAST, ROOT) = (u'|-- ', u'`-- ', u'| ', u' ', u'')
def rec(x, indent, sym):
line = indent + sym + show(x)
xs = kids(x)
if len(xs) == 0:
return line
else:
if sym == MID:
next_indent = indent + CONT
elif sym == ROOT:
next_indent = indent + ROOT
else:
next_indent = indent + LAST
syms = [MID] * (len(xs) - 1) + [END]
lines = [rec(x, next_indent, sym) for x, sym in zip(xs, syms)]
return u'\n'.join([line] + lines)
return rec(x, u'', ROOT)
|
def pretty_tree(x, kids, show)
|
(a, (a -> list(a)), (a -> str)) -> str
Returns a pseudographic tree representation of x similar to the tree command
in Unix.
| 3.076451
| 3.42443
| 0.898383
|
def compile_spec(spec):
name, args = spec
return name, re.compile(*args)
compiled = [compile_spec(s) for s in specs]
def match_specs(specs, str, i, position):
line, pos = position
for type, regexp in specs:
m = regexp.match(str, i)
if m is not None:
value = m.group()
nls = value.count(u'\n')
n_line = line + nls
if nls == 0:
n_pos = pos + len(value)
else:
n_pos = len(value) - value.rfind(u'\n') - 1
return Token(type, value, (line, pos + 1), (n_line, n_pos))
else:
errline = str.splitlines()[line - 1]
raise LexerError((line, pos + 1), errline)
def f(str):
length = len(str)
line, pos = 1, 0
i = 0
while i < length:
t = match_specs(compiled, str, i, (line, pos))
yield t
line, pos = t.end
i += len(t.value)
return f
|
def make_tokenizer(specs)
|
[(str, (str, int?))] -> (str -> Iterable(Token))
| 2.858832
| 2.802692
| 1.02003
|
if s.pos >= len(tokens):
return None, s
else:
raise NoParseError(u'should have reached <EOF>', s)
|
def finished(tokens, s)
|
Parser(a, None)
Throws an exception if any tokens are left in the input unparsed.
| 11.552857
| 10.272532
| 1.124636
|
@Parser
def _many(tokens, s):
res = []
try:
while True:
(v, s) = p.run(tokens, s)
res.append(v)
except NoParseError, e:
return res, State(s.pos, e.state.max)
_many.name = u'{ %s }' % p.name
return _many
|
def many(p)
|
Parser(a, b) -> Parser(a, [b])
Returns a parser that infinitely applies the parser p to the input sequence
of tokens while it successfully parsers them. The resulting parser returns a
list of parsed values.
| 6.395013
| 6.190862
| 1.032976
|
@Parser
def _some(tokens, s):
if s.pos >= len(tokens):
raise NoParseError(u'no tokens left in the stream', s)
else:
t = tokens[s.pos]
if pred(t):
pos = s.pos + 1
s2 = State(pos, max(pos, s.max))
if debug:
log.debug(u'*matched* "%s", new state = %s' % (t, s2))
return t, s2
else:
if debug:
log.debug(u'failed "%s", state = %s' % (t, s))
raise NoParseError(u'got unexpected token', s)
_some.name = u'(some)'
return _some
|
def some(pred)
|
(a -> bool) -> Parser(a, a)
Returns a parser that parses a token if it satisfies a predicate pred.
| 3.9609
| 3.963637
| 0.99931
|
name = getattr(value, 'name', value)
return some(lambda t: t == value).named(u'(a "%s")' % (name,))
|
def a(value)
|
Eq(a) -> Parser(a, a)
Returns a parser that parses a token that is equal to the value value.
| 11.969766
| 11.581596
| 1.033516
|
@Parser
def _oneplus(tokens, s):
(v1, s2) = p.run(tokens, s)
(v2, s3) = many(p).run(tokens, s2)
return [v1] + v2, s3
_oneplus.name = u'(%s , { %s })' % (p.name, p.name)
return _oneplus
|
def oneplus(p)
|
Parser(a, b) -> Parser(a, [b])
Returns a parser that applies the parser p one or more times.
| 4.822523
| 4.430807
| 1.088407
|
@Parser
def f(tokens, s):
return suspension().run(tokens, s)
return f
|
def with_forward_decls(suspension)
|
(None -> Parser(a, b)) -> Parser(a, b)
Returns a parser that computes itself lazily as a result of the suspension
provided. It is needed when some parsers contain forward references to
parsers defined later and such references are cyclic. See examples for more
details.
| 17.382368
| 15.889873
| 1.093927
|
f = getattr(p, 'run', p)
if debug:
setattr(self, '_run', f)
else:
setattr(self, 'run', f)
self.named(getattr(p, 'name', p.__doc__))
|
def define(self, p)
|
Defines a parser wrapped into this object.
| 5.794494
| 4.914608
| 1.179035
|
if debug:
log.debug(u'trying %s' % self.name)
return self._run(tokens, s)
|
def run(self, tokens, s)
|
Sequence(a), State -> (b, State)
Runs a parser wrapped into this object.
| 7.918938
| 7.833138
| 1.010953
|
try:
(tree, _) = self.run(tokens, State())
return tree
except NoParseError, e:
max = e.state.max
if len(tokens) > max:
tok = tokens[max]
else:
tok = u'<EOF>'
raise NoParseError(u'%s: %s' % (e.msg, tok), e.state)
|
def parse(self, tokens)
|
Sequence(a) -> b
Applies the parser to a sequence of tokens producing a parsing result.
It provides a way to invoke a parser hiding details related to the
parser state. Also it makes error messages more readable by specifying
the position of the rightmost token that has been reached.
| 4.432936
| 4.377189
| 1.012736
|
@Parser
def _bind(tokens, s):
(v, s2) = self.run(tokens, s)
return f(v).run(tokens, s2)
_bind.name = u'(%s >>=)' % (self.name,)
return _bind
|
def bind(self, f)
|
Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c)
NOTE: A monadic bind function. It is used internally to implement other
combinators. Functions bind and pure make the Parser a Monad.
| 8.778764
| 7.257623
| 1.209592
|
self.is_done.clear() # hold is_done until the sound is played
if self.sr != sound.sr:
raise ValueError('You can only play sound with a samplerate of {} (here {}). Use the Sound.resample method for instance.', self.sr, sound.sr)
if sound in self.sounds:
self.remove(sound)
with self.chunk_available:
self.sounds.append(sound)
sound.playing = True
self.chunk_available.notify()
self.is_done.wait()
|
def play(self, sound)
|
Adds and plays a new Sound to the Sampler.
:param sound: sound to play
.. note:: If the sound is already playing, it will restart from the beginning.
| 6.671897
| 7.163206
| 0.931412
|
with self.chunk_available:
sound.playing = False
self.sounds.remove(sound)
|
def remove(self, sound)
|
Remove a currently played sound.
| 11.864701
| 10.582732
| 1.121138
|
with self.chunk_available:
while True:
playing_sounds = [s for s in self.sounds if s.playing]
chunks = []
for s in playing_sounds:
try:
chunks.append(next(s.chunks))
except StopIteration:
s.playing = False
self.sounds.remove(s)
self.is_done.set() # sound was played, release is_done to end the wait in play
if chunks:
break
self.chunk_available.wait()
return numpy.mean(chunks, axis=0)
|
def next_chunks(self)
|
Gets a new chunk from all played sound and mix them together.
| 4.84423
| 4.047424
| 1.196867
|
self.running = True
def chunks_producer():
while self.running:
self.chunks.put(self.next_chunks())
t = Thread(target=chunks_producer)
t.start()
with self.BackendStream(samplerate=self.sr, channels=1) as stream:
while self.running:
try:
stream.write(self.chunks.get(timeout=self.timeout)) # timeout so stream.write() thread can exit
except Empty:
self.running = False
|
def run(self)
|
Play loop, i.e. send all sound chunk by chunk to the soundcard.
| 5.161837
| 4.283437
| 1.205069
|
root = Element('UsernameToken', ns=wssens)
u = Element('Username', ns=wssens)
u.setText(self.username)
root.append(u)
p = Element('Password', ns=wssens)
p.setText(self.password)
if self.password_digest:
p.set("Type", wsdigest)
p.setText(self.password_digest)
root.append(p)
if self.nonce is not None:
n = Element('Nonce', ns=wssens)
if self.nonce_has_encoding:
n.set("EncodingType", nonce_encoding_type)
n.setText(self.nonce)
root.append(n)
if self.created is not None:
n = Element('Created', ns=wsuns)
n.setText(str(DateTime(self.created)))
root.append(n)
return root
|
def xml(self)
|
Get xml representation of the object.
@return: The root node.
@rtype: L{Element}
| 2.803912
| 2.810373
| 0.997701
|
ns = attr.namespace()
skip = (
Namespace.xmlns[1],
'http://schemas.xmlsoap.org/soap/encoding/',
'http://schemas.xmlsoap.org/soap/envelope/',
'http://www.w3.org/2003/05/soap-envelope',
)
return ( Namespace.xs(ns) or ns[1] in skip )
|
def skip(self, attr)
|
Get whether to skip (filter-out) the specified attribute.
@param attr: An attribute.
@type attr: I{Attribute}
@return: True if should be skipped.
@rtype: bool
| 4.126132
| 4.11469
| 1.002781
|
sorted = []
processed = set()
for key, deps in dependency_tree.iteritems():
_sort_r(sorted, processed, key, deps, dependency_tree)
return sorted
|
def dependency_sort(dependency_tree)
|
Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containing an object and its dependency list, as given in the input
dependency tree.
If B is directly or indirectly dependent on A and they are not both a part
of the same dependency cycle (i.e. then A is neither directly nor
indirectly dependent on B) then A needs to come before B.
If A and B are a part of the same dependency cycle, i.e. if they are both
directly or indirectly dependent on each other, then it does not matter
which comes first.
Any entries found listed as dependencies, but that do not have their own
dependencies listed as well, are logged & ignored.
@return: The sorted items.
@rtype: list
| 4.934414
| 6.803833
| 0.72524
|
if key in processed:
return
processed.add(key)
for dep_key in deps:
dep_deps = dependency_tree.get(dep_key)
if dep_deps is None:
log.debug('"%s" not found, skipped', Repr(dep_key))
continue
_sort_r(sorted, processed, dep_key, dep_deps, dependency_tree)
sorted.append((key, deps))
|
def _sort_r(sorted, processed, key, deps, dependency_tree)
|
Recursive topological sort implementation.
| 2.586328
| 2.665635
| 0.970248
|
cached = self.resolved_cache.get(nobuiltin)
if cached is not None:
return cached
resolved = self.__resolve_type(nobuiltin)
self.resolved_cache[nobuiltin] = resolved
return resolved
|
def resolve(self, nobuiltin=False)
|
Resolve the node's type reference and return the referenced type node.
Returns self if the type is defined locally, e.g. as a <complexType>
subnode. Otherwise returns the referenced external node.
@param nobuiltin: Flag indicating whether resolving to XSD built-in
types should not be allowed.
@return: The resolved (true) type.
@rtype: L{SchemaObject}
| 3.098911
| 3.505009
| 0.884138
|
# There is no need for a recursive implementation here since a node can
# reference an external type node but XSD specification explicitly
# states that that external node must not be a reference to yet another
# node.
qref = self.qref()
if qref is None:
return self
query = TypeQuery(qref)
query.history = [self]
log.debug("%s, resolving: %s\n using:%s", self.id, qref, query)
resolved = query.execute(self.schema)
if resolved is None:
log.debug(self.schema)
raise TypeNotFound(qref)
if resolved.builtin() and nobuiltin:
return self
return resolved
|
def __resolve_type(self, nobuiltin=False)
|
Private resolve() worker without any result caching.
@param nobuiltin: Flag indicating whether resolving to XSD built-in
types should not be allowed.
@return: The resolved (true) type.
@rtype: L{SchemaObject}
| 8.439309
| 8.527486
| 0.98966
|
if self.type is None and self.ref is None and self.root.isempty():
self.type = self.anytype()
|
def implany(self)
|
Set the type to <xsd:any/> when implicit.
An element has an implicit <xsd:any/> type when it has no body and no
explicitly defined type.
@return: self
@rtype: L{Element}
| 10.817488
| 9.495407
| 1.139234
|
e = self.__deref()
if e is not None:
return e.namespace(prefix)
return super(Element, self).namespace()
|
def namespace(self, prefix=None)
|
Get this schema element's target namespace.
In case of reference elements, the target namespace is defined by the
referenced and not the referencing element node.
@param prefix: The default prefix.
@type prefix: str
@return: The schema element's target namespace
@rtype: (I{prefix},I{URI})
| 6.246705
| 8.787756
| 0.710842
|
if self.opened:
return
self.opened = True
log.debug("%s, importing ns='%s', location='%s'", self.id, self.ns[1],
self.location)
result = self.__locate()
if result is None:
if self.location is None:
log.debug("imported schema (%s) not-found", self.ns[1])
else:
url = self.location
if "://" not in url:
url = urljoin(self.schema.baseurl, url)
result = (loaded_schemata.get(url) or
self.__download(url, loaded_schemata, options))
log.debug("imported:\n%s", result)
return result
|
def open(self, options, loaded_schemata)
|
Open and import the referenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
@return: The referenced schema.
@rtype: L{Schema}
| 4.754375
| 4.544425
| 1.046199
|
if self.ns[1] != self.schema.tns[1]:
return self.schema.locate(self.ns)
|
def __locate(self)
|
Find the schema locally.
| 11.414183
| 7.76327
| 1.47028
|
try:
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set("url", url)
return self.schema.instance(root, url, loaded_schemata, options)
except TransportError:
msg = "import schema (%s) at (%s), failed" % (self.ns[1], url)
log.error("%s, %s", self.id, msg, exc_info=True)
raise Exception(msg)
|
def __download(self, url, loaded_schemata, options)
|
Download the schema.
| 5.702151
| 5.624776
| 1.013756
|
TNS = "targetNamespace"
tns = root.get(TNS)
if tns is None:
tns = self.schema.tns[1]
root.set(TNS, tns)
else:
if self.schema.tns[1] != tns:
raise Exception, "%s mismatch" % TNS
|
def __applytns(self, root)
|
Make sure included schema has the same target namespace.
| 3.733698
| 3.007693
| 1.241383
|
if not self.__resolved:
self.do_resolve(definitions)
self.__resolved = True
|
def resolve(self, definitions)
|
Resolve named references to other WSDL objects.
Can be safely called multiple times.
@param definitions: A definitions object.
@type definitions: L{Definitions}
| 5.200476
| 6.909801
| 0.752623
|
tns = root.get("targetNamespace")
prefix = root.findPrefix(tns)
if prefix is None:
log.debug("warning: tns (%s), not mapped to prefix", tns)
prefix = "tns"
return (prefix, tns)
|
def mktns(self, root)
|
Get/create the target namespace.
| 5.475588
| 5.018282
| 1.091128
|
for imp in self.imports:
imp.load(self, imported_definitions)
|
def open_imports(self, imported_definitions)
|
Import the I{imported} WSDLs.
| 6.759464
| 5.659167
| 1.194427
|
bindings = {
"document/literal": Document(self),
"rpc/literal": RPC(self),
"rpc/encoded": Encoded(self)}
for p in service.ports:
binding = p.binding
ptype = p.binding.type
operations = p.binding.type.operations.values()
for name in (op.name for op in operations):
m = Facade("Method")
m.name = name
m.location = p.location
m.binding = Facade("binding")
op = binding.operation(name)
m.soap = op.soap
key = "/".join((op.soap.style, op.soap.input.body.use))
m.binding.input = bindings.get(key)
key = "/".join((op.soap.style, op.soap.output.body.use))
m.binding.output = bindings.get(key)
p.methods[name] = m
|
def add_methods(self, service)
|
Build method view for service.
| 4.337395
| 4.350185
| 0.99706
|
definitions.types += d.types
definitions.messages.update(d.messages)
definitions.port_types.update(d.port_types)
definitions.bindings.update(d.bindings)
self.imported = d
log.debug("imported (WSDL):\n%s", d)
|
def import_definitions(self, definitions, d)
|
Import/merge WSDL definitions.
| 4.99566
| 3.516247
| 1.420736
|
if not definitions.types:
root = Element("types", ns=wsdlns)
definitions.root.insert(root)
types = Types(root, definitions)
definitions.types.append(types)
else:
types = definitions.types[-1]
types.root.append(d.root)
log.debug("imported (XSD):\n%s", d.root)
|
def import_schema(self, definitions, d)
|
Import schema as <types/> content.
| 5.533428
| 5.277761
| 1.048442
|
try:
return self.operations[name]
except Exception, e:
raise MethodNotFound(name)
|
def operation(self, name)
|
Shortcut used to get a contained operation by name.
@param name: An operation name.
@type name: str
@return: The named operation.
@rtype: Operation
@raise L{MethodNotFound}: When not found.
| 4.73238
| 4.664006
| 1.01466
|
for ns in (soapns, soap12ns):
sr = self.root.getChild("binding", ns=ns)
if sr is not None:
return sr
|
def soaproot(self)
|
Get the soap:binding.
| 6.89195
| 5.425249
| 1.270347
|
self.__resolveport(definitions)
for op in self.operations.values():
self.__resolvesoapbody(definitions, op)
self.__resolveheaders(definitions, op)
self.__resolvefaults(definitions, op)
|
def do_resolve(self, definitions)
|
Resolve named references to other WSDL objects. This includes
cross-linking information (from) the portType (to) the I{SOAP} protocol
information on the binding for each operation.
@param definitions: A definitions object.
@type definitions: L{Definitions}
| 5.603264
| 4.512428
| 1.24174
|
ref = qualify(self.type, self.root, definitions.tns)
port_type = definitions.port_types.get(ref)
if port_type is None:
raise Exception("portType '%s', not-found" % (self.type,))
# Later on we will require access to the message data referenced by
# this port_type instance, and in order for those data references to be
# available, port_type first needs to dereference its message
# identification string. The only scenario where the port_type might
# possibly not have already resolved its references, and where this
# explicit resolve() call is required, is if we are dealing with a
# recursive WSDL import chain.
port_type.resolve(definitions)
self.type = port_type
|
def __resolveport(self, definitions)
|
Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions}
| 10.890443
| 11.039663
| 0.986483
|
for p in self.ports:
if p.name == name:
return p
|
def port(self, name)
|
Locate a port by name.
@param name: A port name.
@type name: str
@return: The port object.
@rtype: L{Port}
| 3.341351
| 5.068485
| 0.659241
|
filtered = []
for p in self.ports:
ref = qualify(p.binding, self.root, definitions.tns)
binding = definitions.bindings.get(ref)
if binding is None:
raise Exception("binding '%s', not-found" % (p.binding,))
if binding.soap is None:
log.debug("binding '%s' - not a SOAP binding, discarded",
binding.name)
continue
# After we have been resolved, our caller will expect that the
# binding we are referencing has been fully constructed, i.e.
# resolved, as well. The only scenario where the operations binding
# might possibly not have already resolved its references, and
# where this explicit resolve() call is required, is if we are
# dealing with a recursive WSDL import chain.
binding.resolve(definitions)
p.binding = binding
filtered.append(p)
self.ports = filtered
|
def do_resolve(self, definitions)
|
Resolve named references to other WSDL objects. Ports without SOAP
bindings are discarded.
@param definitions: A definitions object.
@type definitions: L{Definitions}
| 8.976488
| 7.706214
| 1.164838
|
fn = cls.tags.get(root.name)
if fn is not None:
return fn(root, definitions)
|
def create(cls, root, definitions)
|
Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param definitions: A definitions object.
@type definitions: L{Definitions}
@return: The created object.
@rtype: L{WObject}
| 5.340991
| 5.502786
| 0.970598
|
soapenv = replyroot.getChild("Envelope", envns)
soapenv.promotePrefixes()
soapbody = soapenv.getChild("Body", envns)
soapbody = self.multiref.process(soapbody)
nodes = self.replycontent(method, soapbody)
rtypes = self.returned_types(method)
if len(rtypes) > 1:
return self.replycomposite(rtypes, nodes)
if len(rtypes) == 0:
return
if rtypes[0].multi_occurrence():
return self.replylist(rtypes[0], nodes)
if len(nodes):
resolved = rtypes[0].resolve(nobuiltin=True)
return self.unmarshaller().process(nodes[0], resolved)
|
def get_reply(self, method, replyroot)
|
Process the I{reply} for the specified I{method} by unmarshalling it
into into Python object(s).
@param method: The name of the invoked method.
@type method: str
@param replyroot: The reply XML root node received after invoking the
specified method.
@type replyroot: L{Element}
@return: The unmarshalled reply. The returned value is an L{Object} or
a I{list} depending on whether the service returns a single object
or a collection.
@rtype: L{Object} or I{list}
| 5.411273
| 5.614103
| 0.963871
|
resolved = rt.resolve(nobuiltin=True)
unmarshaller = self.unmarshaller()
return [unmarshaller.process(node, resolved) for node in nodes]
|
def replylist(self, rt, nodes)
|
Construct a I{list} reply.
Called for replies with possible multiple occurrences.
@param rt: The return I{type}.
@type rt: L{suds.xsd.sxbase.SchemaObject}
@param nodes: A collection of XML nodes.
@type nodes: [L{Element},...]
@return: A list of I{unmarshalled} objects.
@rtype: [L{Object},...]
| 11.212152
| 10.053699
| 1.115226
|
marshaller = self.marshaller()
if isinstance(object, (list, tuple)):
return [self.mkheader(method, hdef, item) for item in object]
content = Content(tag=hdef[0], value=object, type=hdef[1])
return marshaller.process(content)
|
def mkheader(self, method, hdef, object)
|
Builds a soapheader for the specified I{method} using the header
definition (hdef) and the specified value (object).
@param method: A method name.
@type method: str
@param hdef: A header definition.
@type hdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject})
@param object: The header value.
@type object: any
@return: The parameter fragment.
@rtype: L{Element}
| 4.825099
| 4.485503
| 1.07571
|
env = Element("Envelope", ns=envns)
env.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
env.append(header)
env.append(body)
return env
|
def envelope(self, header, body)
|
Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the body and header.
@rtype: L{Element}
| 7.429801
| 8.806832
| 0.843641
|
header = Element("Header", ns=envns)
header.append(content)
return header
|
def header(self, content)
|
Build the B{<Body/>} for a SOAP outbound message.
@param content: The header content.
@type content: L{Element}
@return: The SOAP body fragment.
@rtype: L{Element}
| 9.335575
| 10.739603
| 0.869266
|
content = []
wsse = self.options().wsse
if wsse is not None:
content.append(wsse.xml())
headers = self.options().soapheaders
if not isinstance(headers, (tuple, list, dict)):
headers = (headers,)
elif not headers:
return content
pts = self.headpart_types(method)
if isinstance(headers, (tuple, list)):
n = 0
for header in headers:
if isinstance(header, Element):
content.append(deepcopy(header))
continue
if len(pts) == n:
break
h = self.mkheader(method, pts[n], header)
ns = pts[n][1].namespace("ns0")
h.setPrefix(ns[0], ns[1])
content.append(h)
n += 1
else:
for pt in pts:
header = headers.get(pt[0])
if header is None:
continue
h = self.mkheader(method, pt, header)
ns = pt[1].namespace("ns0")
h.setPrefix(ns[0], ns[1])
content.append(h)
return content
|
def headercontent(self, method)
|
Get the content for the SOAP I{Header} node.
@param method: A service method.
@type method: I{service.Method}
@return: The XML content for the <body/>.
@rtype: [L{Element},...]
| 2.878938
| 2.803956
| 1.026741
|
if input:
parts = method.soap.input.body.parts
else:
parts = method.soap.output.body.parts
return [self.__part_type(p, input) for p in parts]
|
def bodypart_types(self, method, input=True)
|
Get a list of I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
| 3.824984
| 4.262036
| 0.897454
|
if input:
headers = method.soap.input.headers
else:
headers = method.soap.output.headers
return [self.__part_type(h.part, input) for h in headers]
|
def headpart_types(self, method, input=True)
|
Get a list of header I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
| 4.933511
| 4.93157
| 1.000394
|
if part.element is None:
query = TypeQuery(part.type)
else:
query = ElementQuery(part.element)
part_type = query.execute(self.schema())
if part_type is None:
raise TypeNotFound(query.ref)
if part.type is not None:
part_type = PartElement(part.name, part_type)
if not input:
return part_type
if part_type.name is None:
return part.name, part_type
return part_type.name, part_type
|
def __part_type(self, part, input)
|
Get a I{parameter definition} (pdef) defined for a given body or header
message part.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param part: A service method input or output part.
@type part: I{suds.wsdl.Part}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
| 3.706626
| 3.730729
| 0.993539
|
if value is None:
value = node.getText()
if isinstance(value, Object):
known = cls.known(value)
if known.name is None:
return node
tm = known.name, known.namespace()
else:
tm = cls.types.get(value.__class__, cls.types.get(str))
cls.manual(node, *tm)
return node
|
def auto(cls, node, value=None)
|
Automatically set the node's xsi:type attribute based on either
I{value}'s or the node text's class. When I{value} is an unmapped
class, the default type (xs:any) is set.
@param node: XML node.
@type node: L{sax.element.Element}
@param value: Object that is or would be the node's text.
@type value: I{any}
@return: Specified node.
@rtype: L{sax.element.Element}
| 5.674137
| 5.709319
| 0.993838
|
xta = ":".join((Namespace.xsins[0], "type"))
node.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
if ns is None:
node.set(xta, tval)
else:
ns = cls.genprefix(node, ns)
qname = ":".join((ns[0], tval))
node.set(xta, qname)
node.addPrefix(ns[0], ns[1])
return node
|
def manual(cls, node, tval, ns=None)
|
Set the node's xsi:type attribute based on either I{value}'s or the
node text's class. Then adds the referenced prefix(s) to the node's
prefix mapping.
@param node: XML node.
@type node: L{sax.element.Element}
@param tval: XSD schema type name.
@type tval: str
@param ns: I{tval} XML namespace.
@type ns: (prefix, URI)
@return: Specified node.
@rtype: L{sax.element.Element}
| 4.325462
| 4.169951
| 1.037293
|
for i in range(1, 1024):
prefix = "ns%d" % (i,)
uri = node.resolvePrefix(prefix, default=None)
if uri in (None, ns[1]):
return prefix, ns[1]
raise Exception("auto prefix, exhausted")
|
def genprefix(cls, node, ns)
|
Generate a prefix.
@param node: XML node on which the prefix will be used.
@type node: L{sax.element.Element}
@param ns: Namespace needing a unique prefix.
@type ns: (prefix, URI)
@return: I{ns} with a new prefix.
@rtype: (prefix, URI)
| 6.047262
| 5.051609
| 1.197096
|
try:
filename = self.__filename(id)
self.__remove_if_expired(filename)
return self.__open(filename, "rb")
except Exception:
pass
|
def _getf(self, id)
|
Open a cached file with the given id for reading.
| 6.183314
| 5.416666
| 1.141535
|
suffix = self.fnsuffix()
filename = "%s-%s.%s" % (self.fnprefix, id, suffix)
return os.path.join(self.location, filename)
|
def __filename(self, id)
|
Return the cache file name for an entry with a given id.
| 5.165777
| 5.156257
| 1.001846
|
if not FileCache.__default_location:
tmp = tempfile.mkdtemp("suds-default-cache")
FileCache.__default_location = tmp
import atexit
atexit.register(FileCache.__remove_default_location)
return FileCache.__default_location
|
def __get_default_location()
|
Returns the current process's default cache location folder.
The folder is determined lazily on first call.
| 4.286535
| 4.139744
| 1.035459
|
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except Exception:
log.debug(self.location, exc_info=1)
return self
|
def __mktmp(self)
|
Create the I{location} folder if it does not already exist.
| 3.462076
| 2.72021
| 1.272724
|
if not self.duration:
return
created = datetime.datetime.fromtimestamp(os.path.getctime(filename))
expired = created + self.duration
if expired < datetime.datetime.now():
os.remove(filename)
log.debug("%s expired, deleted", filename)
|
def __remove_if_expired(self, filename)
|
Remove a cached file entry if it expired.
@param filename: The file name.
@type filename: str
| 2.899867
| 3.190895
| 0.908794
|
tns = root.get('targetNamespace')
if len(self.tns):
matched = ( tns in self.tns )
else:
matched = 1
itself = ( ns == tns )
return ( matched and not itself )
|
def match(self, root, ns)
|
Match by I{targetNamespace} excluding those that
are equal to the specified namespace to prevent
adding an import to itself.
@param root: A schema root.
@type root: L{Element}
| 6.836073
| 6.565776
| 1.041167
|
if self.urlopener is None:
return urllib2.build_opener(*self.u2handlers())
return self.urlopener
|
def u2opener(self)
|
Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector}
| 4.567792
| 4.821627
| 0.947355
|
try:
part = urllib2.__version__.split('.', 1)
return float('.'.join(part))
except Exception, e:
log.exception(e)
return 0
|
def u2ver(self)
|
Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float
| 6.416796
| 4.23201
| 1.516253
|
def any_contains_any(strings, candidates):
for string in strings:
for c in candidates:
if c in string:
return True
|
Whether any of the strings contains any of the candidates.
| null | null | null |
|
def path_to_URL(path, escape=True):
# We do not use urllib's builtin pathname2url() function since:
# - it has been commented with 'not recommended for general use'
# - it does not seem to work the same on Windows and non-Windows platforms
# (result starts with /// on Windows but does not on others)
# - urllib implementation prior to Python 2.5 used to quote ':' characters
# as '|' which would confuse pip on Windows.
url = os.path.abspath(path)
for sep in (os.sep, os.altsep):
if sep and sep != "/":
url = url.replace(sep, "/")
if escape:
# Must not escape ':' or '/' or Python will not recognize those URLs
# correctly. Detected on Windows 7 SP1 x64 with Python 3.4.0, but doing
# this always does not hurt since both are valid ASCII characters.
no_protocol_URL = url_quote(url, safe=":/")
else:
no_protocol_URL = url
return "file:///%s" % (no_protocol_URL,)
|
Convert a local file path to a absolute path file protocol URL.
| null | null | null |
|
def requirement_spec(package_name, *args):
if not args or args == (None,):
return package_name
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list, tuple)):
operator, version = version_spec
else:
assert isinstance(version_spec, str)
operator = "=="
version = version_spec
version_specs.append("%s%s" % (operator, version))
return "%s%s" % (package_name, ",".join(version_specs))
|
Identifier used when specifying a requirement to pip or setuptools.
| null | null | null |
|
def script_folder(script_path):
# There exist modules whose __file__ attribute does not correspond directly
# to a disk file, e.g. modules imported from inside zip archives.
if os.path.isfile(script_path):
return _rel_path(os.path.dirname(script_path)) or "."
|
Return the given script's folder or None if it can not be determined.
Script is identified by its __file__ attribute. If the given __file__
attribute value contains no path information, it is expected to identify an
existing file in the current working folder.
Returned folder may be specified relative to the current working folder
and, if determined, will never be an empty string.
Typical use case for calling this function is from a regular stand-alone
script and not a frozen module or a module imported from the disk, a
zip-file, an external database or any other such source. Such callers can
safely assume they have a valid __file__ attribute available.
| null | null | null |
|
def path_iter(path):
parts = []
while path:
path, item = os.path.split(path)
if item:
parts.append(item)
return reversed(parts)
|
Returns an iterator over all the file & folder names in a path.
| null | null | null |
|
tag = wrapper[1].name
ns = wrapper[1].namespace("ns0")
return Element(tag, ns=ns)
|
def document(self, wrapper)
|
Get the document root. For I{document/literal}, this is the name of the
wrapper element qualified by the schema's target namespace.
@param wrapper: The method name.
@type wrapper: L{xsd.sxbase.SchemaObject}
@return: A root element.
@rtype: L{Element}
| 13.726094
| 12.262532
| 1.119352
|
if isinstance(object, (list, tuple)):
return [self.mkparam(method, pdef, item) for item in object]
return super(Document, self).mkparam(method, pdef, object)
|
def mkparam(self, method, pdef, object)
|
Expand list parameters into individual parameters each with the type
information. This is because in document arrays are simply
multi-occurrence elements.
| 2.648542
| 2.430124
| 1.089879
|
pts = self.bodypart_types(method)
if not method.soap.input.body.wrapped:
return pts
pt = pts[0][1].resolve()
return [(c.name, c, a) for c, a in pt if not c.isattr()]
|
def param_defs(self, method)
|
Get parameter definitions for document literal.
| 16.635231
| 11.886828
| 1.399468
|
assert isinstance(s, basestring)
if isinstance(s, unicode):
return s.encode(encoding, errors)
if s and encoding != input_encoding:
return s.decode(input_encoding, errors).encode(encoding, errors)
return s
|
def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict")
|
Returns a byte string version of 's', encoded as specified in 'encoding'.
Accepts str & unicode objects, interpreting non-unicode strings as byte
strings encoded using the given input encoding.
| 2.245214
| 2.395551
| 0.937243
|
dt = datetime.datetime(2000, 1, 1, time.hour, time.minute,
time.second, time.microsecond)
dt += datetime.timedelta(microseconds=1)
return dt.time()
|
def _bump_up_time_by_microsecond(time)
|
Helper function bumping up the given datetime.time by a microsecond,
cycling around silently to 00:00:00.0 in case of an overflow.
@param time: Time object.
@type time: B{datetime}.I{time}
@return: Time object.
@rtype: B{datetime}.I{time}
| 2.29833
| 2.905539
| 0.791017
|
year = int(match_object.group("year"))
month = int(match_object.group("month"))
day = int(match_object.group("day"))
return datetime.date(year, month, day)
|
def _date_from_match(match_object)
|
Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{date}
| 1.699156
| 2.129108
| 0.79806
|
hour = int(match_object.group('hour'))
minute = int(match_object.group('minute'))
second = int(match_object.group('second'))
subsecond = match_object.group('subsecond')
round_up = False
microsecond = 0
if subsecond:
round_up = len(subsecond) > 6 and int(subsecond[6]) >= 5
subsecond = subsecond[:6]
microsecond = int(subsecond + "0" * (6 - len(subsecond)))
return datetime.time(hour, minute, second, microsecond), round_up
|
def _time_from_match(match_object)
|
Create a time object from a regular expression match.
Returns the time object and information whether the resulting time should
be bumped up by one microsecond due to microsecond rounding.
Subsecond information is rounded to microseconds due to a restriction in
the python datetime.datetime/time implementation.
The regular expression match is expected to be from _RE_DATETIME or
_RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: Time object + rounding flag.
@rtype: tuple of B{datetime}.I{time} and bool
| 2.161818
| 2.251372
| 0.960223
|
tz_utc = match_object.group("tz_utc")
if tz_utc:
return UtcTimezone()
tz_sign = match_object.group("tz_sign")
if not tz_sign:
return
h = int(match_object.group("tz_hour") or 0)
m = int(match_object.group("tz_minute") or 0)
if h == 0 and m == 0:
return UtcTimezone()
# Python limitation - timezone offsets larger than one day (in absolute)
# will cause operations depending on tzinfo.utcoffset() to fail, e.g.
# comparing two timezone aware datetime.datetime/time objects.
if h >= 24:
raise ValueError("timezone indicator too large")
tz_delta = datetime.timedelta(hours=h, minutes=m)
if tz_sign == "-":
tz_delta *= -1
return FixedOffsetTimezone(tz_delta)
|
def _tzinfo_from_match(match_object)
|
Create a timezone information object from a regular expression match.
The regular expression match is expected to be from _RE_DATE, _RE_DATETIME
or _RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A timezone information object.
@rtype: B{datetime}.I{tzinfo}
| 3.6019
| 3.877202
| 0.928995
|
match_result = _RE_DATE.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
return _date_from_match(match_result)
|
def __parse(value)
|
Parse the string date.
Supports the subset of ISO8601 used by xsd:date, but is lenient with
what is accepted, handling most reasonable syntax.
Any timezone is parsed but ignored because a) it is meaningless without
a time and b) B{datetime}.I{date} does not support timezone
information.
@param value: A date string.
@type value: str
@return: A date object.
@rtype: B{datetime}.I{date}
| 4.865919
| 5.093557
| 0.955309
|
match_result = _RE_DATETIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
date = _date_from_match(match_result)
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
value = datetime.datetime.combine(date, time)
value = value.replace(tzinfo=tzinfo)
if round_up:
value += datetime.timedelta(microseconds=1)
return value
|
def __parse(value)
|
Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.datetime/time implementation.
@param value: A datetime string.
@type value: str
@return: A datetime object.
@rtype: B{datetime}.I{datetime}
| 3.028232
| 2.902644
| 1.043267
|
match_result = _RE_TIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
if round_up:
time = _bump_up_time_by_microsecond(time)
return time.replace(tzinfo=tzinfo)
|
def __parse(value)
|
Parse the string date.
Supports the subset of ISO8601 used by xsd:time, but is lenient with
what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.time implementation.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time}
| 4.384603
| 4.004408
| 1.094944
|
# total_seconds was introduced in Python 2.7
if hasattr(self.__offset, "total_seconds"):
total_seconds = self.__offset.total_seconds()
else:
total_seconds = (self.__offset.days * 24 * 60 * 60) + \
(self.__offset.seconds)
hours = total_seconds // (60 * 60)
total_seconds -= hours * 60 * 60
minutes = total_seconds // 60
total_seconds -= minutes * 60
seconds = total_seconds // 1
total_seconds -= seconds
if seconds:
return "%+03d:%02d:%02d" % (hours, minutes, seconds)
return "%+03d:%02d" % (hours, minutes)
|
def tzname(self, dt)
|
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
| 1.929656
| 1.861196
| 1.036783
|
node = content.node
if len(node.children) and node.hasText():
return node
attributes = AttrList(node.attributes)
if attributes.rlen() and \
not len(node.children) and \
node.hasText():
p = Factory.property(node.name, node.getText())
return merge(content.data, p)
if len(content.data):
return content.data
lang = attributes.lang()
if content.node.isnil():
return None
if not len(node.children) and content.text is None:
if self.nillable(content):
return None
else:
return Text('', lang=lang)
if isinstance(content.text, basestring):
return Text(content.text, lang=lang)
else:
return content.text
|
def postprocess(self, content)
|
Perform final processing of the resulting data structure as follows:
- Mixed values (children and text) will have a result of the I{content.node}.
- Simi-simple values (attributes, no-children and text) will have a result of a
property object.
- Simple values (no-attributes, no-children with text nodes) will have a string
result equal to the value of the content.node.getText().
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: The post-processed result.
@rtype: I{any}
| 5.276029
| 4.626072
| 1.140499
|
for child in content.node:
cont = Content(child)
cval = self.append(cont)
key = reserved.get(child.name, child.name)
if key in content.data:
v = getattr(content.data, key)
if isinstance(v, list):
v.append(cval)
else:
setattr(content.data, key, [v, cval])
continue
if self.multi_occurrence(cont):
if cval is None:
setattr(content.data, key, [])
else:
setattr(content.data, key, [cval,])
else:
setattr(content.data, key, cval)
|
def append_children(self, content)
|
Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content}
| 3.025117
| 2.982719
| 1.014214
|
if string:
return suds.sax.parser.Parser().parse(string=string)
|
def _parse(string)
|
Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{None}
| 11.147562
| 15.951349
| 0.698848
|
timer = metrics.Timer()
timer.start()
type = self.resolver.find(name)
if type is None:
raise TypeNotFound(name)
if type.enum():
result = sudsobject.Factory.object(name)
for e, a in type.children():
setattr(result, e.name, e.name)
else:
try:
result = self.builder.build(type)
except Exception, e:
log.error("create '%s' failed", name, exc_info=True)
raise BuildError(name, e)
timer.stop()
metrics.log.debug("%s created: %s", name, timer)
return result
|
def create(self, name)
|
Create a WSDL type by name.
@param name: The name of a type defined in the WSDL.
@type name: str
@return: The requested object.
@rtype: L{Object}
| 4.68838
| 4.53044
| 1.034862
|
service = None
if not self.__services:
raise Exception, "No services defined"
if isinstance(name, int):
try:
service = self.__services[name]
name = service.name
except IndexError:
raise ServiceNotFound, "at [%d]" % (name,)
else:
for s in self.__services:
if name == s.name:
service = s
break
if service is None:
raise ServiceNotFound, name
return PortSelector(self.__client, service.ports, name)
|
def __find(self, name)
|
Find a I{service} by name (string) or index (integer).
@param name: The name (or index) of a service.
@type name: int|str
@return: A L{PortSelector} for the found service.
@rtype: L{PortSelector}.
| 3.616242
| 3.10391
| 1.16506
|
ds = self.__client.options.service
if ds is not None:
return self.__find(ds)
|
def __ds(self)
|
Get the I{default} service if defined in the I{options}.
@return: A L{PortSelector} for the I{default} service.
@rtype: L{PortSelector}.
| 14.566179
| 11.867446
| 1.227406
|
return self.__process_reply(reply, status, description)
|
def process_reply(self, reply, status=None, description=None)
|
Re-entry for processing a successful reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code.
@type status: int
@param description: Additional status description.
@type description: I{bytes}
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
| 6.440422
| 10.266122
| 0.627347
|
location = self.__location()
log.debug("sending to (%s)\nmessage:\n%s", location, soapenv)
plugins = PluginContainer(self.options.plugins)
plugins.message.marshalled(envelope=soapenv.root())
if self.options.prettyxml:
soapenv = soapenv.str()
else:
soapenv = soapenv.plain()
soapenv = soapenv.encode("utf-8")
ctx = plugins.message.sending(envelope=soapenv)
soapenv = ctx.envelope
if self.options.nosend:
return RequestContext(self.process_reply, soapenv)
request = suds.transport.Request(location, soapenv)
request.headers = self.__headers()
try:
timer = metrics.Timer()
timer.start()
reply = self.options.transport.send(request)
timer.stop()
metrics.log.debug("waited %s on server reply", timer)
except suds.transport.TransportError, e:
content = e.fp and e.fp.read() or ""
return self.process_reply(content, e.httpcode, tostr(e))
return self.process_reply(reply.message, None, None)
|
def send(self, soapenv)
|
Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param soapenv: A SOAP envelope to send.
@type soapenv: L{Document}
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
| 4.754745
| 4.639486
| 1.024843
|
if status is None:
status = httplib.OK
debug_message = "Reply HTTP status - %d" % (status,)
if status in (httplib.ACCEPTED, httplib.NO_CONTENT):
log.debug(debug_message)
return
#TODO: Consider whether and how to allow plugins to handle error,
# httplib.ACCEPTED & httplib.NO_CONTENT replies as well as successful
# ones.
if status == httplib.OK:
log.debug("%s\n%s", debug_message, reply)
else:
log.debug("%s - %s\n%s", debug_message, description, reply)
plugins = PluginContainer(self.options.plugins)
ctx = plugins.message.received(reply=reply)
reply = ctx.reply
# SOAP standard states that SOAP errors must be accompanied by HTTP
# status code 500 - internal server error:
#
# From SOAP 1.1 specification:
# In case of a SOAP error while processing the request, the SOAP HTTP
# server MUST issue an HTTP 500 "Internal Server Error" response and
# include a SOAP message in the response containing a SOAP Fault
# element (see section 4.4) indicating the SOAP processing error.
#
# From WS-I Basic profile:
# An INSTANCE MUST use a "500 Internal Server Error" HTTP status code
# if the response message is a SOAP Fault.
replyroot = None
if status in (httplib.OK, httplib.INTERNAL_SERVER_ERROR):
replyroot = _parse(reply)
plugins.message.parsed(reply=replyroot)
fault = self.__get_fault(replyroot)
if fault:
if status != httplib.INTERNAL_SERVER_ERROR:
log.warn("Web service reported a SOAP processing fault "
"using an unexpected HTTP status code %d. Reporting "
"as an internal server error.", status)
if self.options.faults:
raise WebFault(fault, replyroot)
return httplib.INTERNAL_SERVER_ERROR, fault
if status != httplib.OK:
if self.options.faults:
#TODO: Use a more specific exception class here.
raise Exception((status, description))
return status, description
if self.options.retxml:
return reply
result = replyroot and self.method.binding.output.get_reply(
self.method, replyroot)
ctx = plugins.message.unmarshalled(reply=result)
result = ctx.reply
if self.options.faults:
return result
return httplib.OK, result
|
def process_reply(self, reply, status, description)
|
Process a web service operation SOAP reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code (None indicates httplib.OK).
@type status: int|I{None}
@param description: Additional status description.
@type description: str
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
| 4.813208
| 4.633045
| 1.038886
|
envns = suds.bindings.binding.envns
soapenv = replyroot and replyroot.getChild("Envelope", envns)
soapbody = soapenv and soapenv.getChild("Body", envns)
fault = soapbody and soapbody.getChild("Fault", envns)
return fault is not None and UmxBasic().process(fault)
|
def __get_fault(self, replyroot)
|
Extract fault information from a SOAP reply.
Returns an I{unmarshalled} fault L{Object} or None in case the given
XML document does not contain a SOAP <Fault> element.
@param replyroot: A SOAP reply message root XML element or None.
@type replyroot: L{Element}|I{None}
@return: A fault object.
@rtype: L{Object}
| 5.432428
| 5.842453
| 0.92982
|
action = self.method.soap.action
if isinstance(action, unicode):
action = action.encode("utf-8")
result = {
"Content-Type": "text/xml; charset=utf-8",
"SOAPAction": action}
result.update(**self.options.headers)
log.debug("headers = %s", result)
return result
|
def __headers(self)
|
Get HTTP headers for a HTTP/HTTPS SOAP request.
@return: A dictionary of header/values.
@rtype: dict
| 4.241982
| 4.099296
| 1.034808
|
simulation = kwargs.pop(self.__injkey)
msg = simulation.get("msg")
if msg is not None:
assert msg.__class__ is suds.byte_str_class
return self.send(_parse(msg))
msg = self.method.binding.input.get_message(self.method, args, kwargs)
log.debug("inject (simulated) send message:\n%s", msg)
reply = simulation.get("reply")
if reply is not None:
assert reply.__class__ is suds.byte_str_class
status = simulation.get("status")
description = simulation.get("description")
if description is None:
description = "injected reply"
return self.process_reply(reply, status, description)
raise Exception("reply or msg injection parameter expected")
|
def invoke(self, args, kwargs)
|
Invoke a specified web service method.
Uses an injected SOAP request/response instead of a regularly
constructed/received one.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param args: Positional arguments for the method invoked.
@type args: list|tuple
@param kwargs: Keyword arguments for the method invoked.
@type kwargs: dict
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
| 5.958014
| 5.676333
| 1.049624
|
if isinstance(url, str):
url.encode("ascii") # Check for non-ASCII characters.
self.url = url
elif sys.version_info < (3, 0):
self.url = url.encode("ascii")
else:
self.url = url.decode("ascii")
|
def __set_URL(self, url)
|
URL is stored as a str internally and must not contain ASCII chars.
Raised exception in case of detected non-ASCII URL characters may be
either UnicodeEncodeError or UnicodeDecodeError, depending on the used
Python version's str type and the exact value passed as URL input data.
| 2.976037
| 3.021469
| 0.984963
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.