code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
'''Open the URL of a repository in the user's browser'''
webbrowser.open(self.format_path(repo, namespace=user, rw=False))
|
def open(self, user=None, repo=None)
|
Open the URL of a repository in the user's browser
| 12.921496 | 10.13607 | 1.274803 |
def request_fetch(self, user, repo, request, pull=False, force=False): #pragma: no cover
'''Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses
'''
raise NotImplementedError
|
Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses
| null | null | null |
|
'''
Decorator for a parameter, use the full length parameter name as specified in the
docopt configuration, like '--verbose'
'''
def decorator(fun):
KeywordArgumentParser._parameter_dict[parameter] = fun
return fun
return decorator
|
def store_parameter(parameter)
|
Decorator for a parameter, use the full length parameter name as specified in the
docopt configuration, like '--verbose'
| 17.296686 | 3.651254 | 4.73719 |
'''
Decorator for an action, the arguments order is not relevant, but it's best
to use the same order as in the docopt for clarity.
'''
def decorator(fun):
KeywordArgumentParser._action_dict[frozenset(args)] = fun
return fun
return decorator
|
def register_action(*args, **kwarg)
|
Decorator for an action, the arguments order is not relevant, but it's best
to use the same order as in the docopt for clarity.
| 10.908072 | 3.50811 | 3.109387 |
'''
This method iterates over the docopt's arguments and matches them against
the parameters list. All leftover values are used to resolve the action to
run, and it will run the action, or run the fallback() method if no action
is found.
'''
self.init()
args = []
missed = []
# go through setters
for arg, value in self.args.items():
if arg in self._parameter_dict:
self._parameter_dict[arg](self, value)
#log.debug('calling setter: {} → {}'.format(arg, value))
elif arg.startswith('--') or arg.startswith('<'):
arg_renamed = arg.lstrip('-<').rstrip('>').replace('-', '_')
if not hasattr(self, arg_renamed):
setattr(self, arg_renamed, value)
#log.debug('auto-setting: self.{} → {}'.format(arg_renamed, value))
else:
#log.debug('keeping: {} → {}'.format(arg, value))
if self.args[arg]:
args.append(arg)
if frozenset(args) in self._action_dict:
#log.debug('running action: {}'.format(self._action_dict[frozenset(args)]))
return self._action_dict[frozenset(args)](self)
else:
return self.fallback()
|
def run(self)
|
This method iterates over the docopt's arguments and matches them against
the parameters list. All leftover values are used to resolve the action to
run, and it will run the action, or run the fallback() method if no action
is found.
| 4.566694 | 2.86338 | 1.594861 |
def signal_fired(sender, object, iface, signal, params):
callback(*params)
return object._bus.subscribe(sender=object._bus_name, object=object._path, iface=self._iface_name, signal=self.__name__, signal_fired=signal_fired)
|
def connect(self, object, callback)
|
Subscribe to the signal.
| 5.858489 | 5.302914 | 1.104768 |
# Python 2 sux
for kwarg in kwargs:
if kwarg not in ("timeout",):
raise TypeError(self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg))
timeout = kwargs.get("timeout", None)
bus_name = auto_bus_name(bus_name)
object_path = auto_object_path(bus_name, object_path)
ret = self.con.call_sync(
bus_name, object_path,
'org.freedesktop.DBus.Introspectable', "Introspect", None, GLib.VariantType.new("(s)"),
0, timeout_to_glib(timeout), None)
if not ret:
raise KeyError("no such object; you might need to pass object path as the 2nd argument for get()")
xml, = ret.unpack()
try:
introspection = ET.fromstring(xml)
except:
raise KeyError("object provides invalid introspection XML")
return CompositeInterface(introspection)(self, bus_name, object_path)
|
def get(self, bus_name, object_path=None, **kwargs)
|
Get a remote object.
Parameters
----------
bus_name : string
Name of the service that exposes this object.
You may start with "." - then org.freedesktop will be automatically prepended.
object_path : string, optional
Path of the object. If not provided, bus_name translated to path format is used.
Returns
-------
ProxyObject implementing all the Interfaces exposed by the remote object.
Note that it inherits from multiple Interfaces, so the method you want to use
may be shadowed by another one, eg. from a newer version of the interface.
Therefore, to interact with only a single interface, use:
>>> bus.get("org.freedesktop.systemd1")["org.freedesktop.systemd1.Manager"]
or simply
>>> bus.get(".systemd1")[".Manager"]
which will give you access to the one specific interface.
| 4.669786 | 4.768229 | 0.979354 |
return NameOwner(self, name, allow_replacement, replace)
|
def request_name(self, name, allow_replacement=True, replace=False)
|
Aquires a bus name.
Returns
-------
NameOwner
An object you can use as a context manager to unown the name later.
| 9.344446 | 6.630024 | 1.409414 |
callback = (lambda con, sender, object, iface, signal, params: signal_fired(sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None
return Subscription(self.con, sender, iface, signal, object, arg0, flags, callback)
|
def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None)
|
Subscribes to matching signals.
Subscribes to signals on connection and invokes signal_fired callback
whenever the signal is received.
To receive signal_fired callback, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
sender : string, optional
Sender name to match on (unique or well-known name) or None to listen from all senders.
iface : string, optional
Interface name to match on or None to match on all interfaces.
signal : string, optional
Signal name to match on or None to match on all signals.
object : string, optional
Object path to match on or None to match on all object paths.
arg0 : string, optional
Contents of first string argument to match on or None to match on all kinds of arguments.
flags : SubscriptionFlags, optional
signal_fired : callable, optional
Invoked when there is a signal matching the requested data.
Parameters: sender, object, iface, signal, params
Returns
-------
Subscription
An object you can use as a context manager to unsubscribe from the signal later.
See Also
--------
See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe
for more information.
| 4.514882 | 4.211843 | 1.071949 |
warnings.warn("own_name() is deprecated, use request_name() instead.", DeprecationWarning)
name_aquired_handler = (lambda con, name: name_aquired()) if name_aquired is not None else None
name_lost_handler = (lambda con, name: name_lost()) if name_lost is not None else None
return NameOwner(self.con, name, flags, name_aquired_handler, name_lost_handler)
|
def own_name(self, name, flags=0, name_aquired=None, name_lost=None)
|
[DEPRECATED] Asynchronously aquires a bus name.
Starts acquiring name on the bus specified by bus_type and calls
name_acquired and name_lost when the name is acquired respectively lost.
To receive name_aquired and name_lost callbacks, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
name : string
Bus name to aquire
flags : NameOwnerFlags, optional
name_aquired : callable, optional
Invoked when name is acquired
name_lost : callable, optional
Invoked when name is lost
Returns
-------
NameOwner
An object you can use as a context manager to unown the name later.
See Also
--------
See https://developer.gnome.org/gio/2.44/gio-Owning-Bus-Names.html#g-bus-own-name
for more information.
| 2.892373 | 3.271092 | 0.884223 |
name_appeared_handler = (lambda con, name, name_owner: name_appeared(name_owner)) if name_appeared is not None else None
name_vanished_handler = (lambda con, name: name_vanished()) if name_vanished is not None else None
return NameWatcher(self.con, name, flags, name_appeared_handler, name_vanished_handler)
|
def watch_name(self, name, flags=0, name_appeared=None, name_vanished=None)
|
Asynchronously watches a bus name.
Starts watching name on the bus specified by bus_type and calls
name_appeared and name_vanished when the name is known to have a owner
respectively known to lose its owner.
To receive name_appeared and name_vanished callbacks, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
name : string
Bus name to watch
flags : NameWatcherFlags, optional
name_appeared : callable, optional
Invoked when name is known to exist
Called as name_appeared(name_owner).
name_vanished : callable, optional
Invoked when name is known to not exist
Returns
-------
NameWatcher
An object you can use as a context manager to unwatch the name later.
See Also
--------
See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name
for more information.
| 3.141972 | 3.193161 | 0.983969 |
return subscription(self.map.setdefault(object, []), callback)
|
def connect(self, object, callback)
|
Subscribe to the signal.
| 23.617846 | 18.385677 | 1.284578 |
for cb in self.map.get(object, []):
cb(*args)
|
def emit(self, object, *args)
|
Emit the signal.
| 5.507771 | 5.287439 | 1.041671 |
global _PROGRESS_BAR, _DFS
# create ticker list
tickers = tickers if isinstance(tickers, list) else tickers.split()
if progress:
_PROGRESS_BAR = _ProgressBar(len(tickers), 'downloaded')
# reset _DFS
_DFS = {}
# set thread count if True
if threads is True:
threads = min([len(tickers), _multitasking.cpu_count()])
# download using threads
if isinstance(threads, int):
_multitasking.set_max_threads(threads)
for i, ticker in enumerate(tickers):
_download_one_threaded(ticker, period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust,
progress=(progress and i > 0))
while len(_DFS) < len(tickers):
_time.sleep(0.01)
# download synchronously
else:
for i, ticker in enumerate(tickers):
data = _download_one(ticker, period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust)
_DFS[ticker.upper()] = data
if progress:
_PROGRESS_BAR.animate()
if progress:
_PROGRESS_BAR.completed()
data = _pd.concat(_DFS.values(), axis=1, keys=_DFS.keys())
if group_by == 'column':
data.columns = data.columns.swaplevel(0, 1)
data.sort_index(level=0, axis=1, inplace=True)
if len(tickers) == 1:
data = _DFS[tickers[0]]
return data
|
def download(tickers, start=None, end=None, actions=False, threads=False,
group_by='column', auto_adjust=False, progress=True,
period="max", interval="1d", prepost=False, **kwargs)
|
Download yahoo tickers
:Parameters:
tickers : str, list
List of tickers to download
period : str
Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
Either Use period parameter or use start and end
interval : str
Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
Intraday data cannot extend last 60 days
start: str
Download start date string (YYYY-MM-DD) or _datetime.
Default is 1900-01-01
end: str
Download end date string (YYYY-MM-DD) or _datetime.
Default is now
group_by : str
Group by 'ticker' or 'column' (default)
prepost : bool
Include Pre and Post market data in results?
Default is False
auto_adjust: bool
Adjust all OHLC automatically? Default is False
actions: bool
Download dividend + stock splits data. Default is False
threads: bool / int
How many threads to use for mass downloading. Default is False
| 2.552037 | 2.535585 | 1.006489 |
url = "{}/v7/finance/quote?symbols={}".format(
self._base_url, self.ticker)
r = _requests.get(url=url).json()["quoteResponse"]["result"]
if len(r) > 0:
return r[0]
return {}
|
def info(self)
|
retreive metadata and currenct price data
| 4.706662 | 3.840987 | 1.225378 |
# Copy and convert the headers dict/object (see comments in
# AsyncHTTPClient.fetch)
request.headers = httputil.HTTPHeaders(request.headers)
request = httpclient._RequestProxy(
request, httpclient.HTTPRequest._DEFAULTS)
# for tornado 4.5.x compatibility
if version_info[0] == 4:
conn = PingableWSClientConnection(io_loop=ioloop.IOLoop.current(),
request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback)
else:
conn = PingableWSClientConnection(request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback,
max_message_size=getattr(websocket, '_default_max_message_size', 10 * 1024 * 1024))
return conn.connect_future
|
def pingable_ws_connect(request=None, on_message_callback=None,
on_ping_callback=None)
|
A variation on websocket_connect that returns a PingableWSClientConnection
with on_ping_callback.
| 3.420503 | 3.3282 | 1.027734 |
# FIXME: support default args
# FIXME: support kwargs
# co_varnames contains both args and local variables, in order.
# We only pick the local variables
asked_arg_names = callback.__code__.co_varnames[:callback.__code__.co_argcount]
asked_arg_values = []
missing_args = []
for asked_arg_name in asked_arg_names:
if asked_arg_name in args:
asked_arg_values.append(args[asked_arg_name])
else:
missing_args.append(asked_arg_name)
if missing_args:
raise TypeError(
'{}() missing required positional argument: {}'.format(
callback.__code__.co_name,
', '.join(missing_args)
)
)
return callback(*asked_arg_values)
|
def call_with_asked_args(callback, args)
|
Call callback with only the args it wants from args
Example
>>> def cb(a):
... return a * 5
>>> print(call_with_asked_args(cb, {'a': 4, 'b': 8}))
20
| 2.688191 | 2.830353 | 0.949772 |
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
self.proxy_base = name
self.absolute_url = absolute_url
self.requested_port = port
@property
def process_args(self):
return {
'port': self.port,
'base_url': self.base_url,
}
def _render_template(self, value):
args = self.process_args
if type(value) is str:
return value.format(**args)
elif type(value) is list:
return [self._render_template(v) for v in value]
elif type(value) is dict:
return {
self._render_template(k): self._render_template(v)
for k, v in value.items()
}
else:
raise ValueError('Value of unrecognized type {}'.format(type(value)))
def get_cmd(self):
if callable(command):
return self._render_template(call_with_asked_args(command, self.process_args))
else:
return self._render_template(command)
def get_env(self):
if callable(environment):
return self._render_template(call_with_asked_args(environment, self.process_args))
else:
return self._render_template(environment)
def get_timeout(self):
return timeout
return _Proxy
|
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port)
|
Create a SuperviseAndProxyHandler subclass with given parameters
| 2.332443 | 2.161718 | 1.078976 |
handlers = []
for sp in server_processes:
handler = _make_serverproxy_handler(
sp.name,
sp.command,
sp.environment,
sp.timeout,
sp.absolute_url,
sp.port,
)
handlers.append((
ujoin(base_url, sp.name, r'(.*)'), handler, dict(state={}),
))
handlers.append((
ujoin(base_url, sp.name), AddSlashHandler
))
return handlers
|
def make_handlers(base_url, server_processes)
|
Get tornado handlers for registered server_processes
| 4.9091 | 4.496531 | 1.091753 |
if not proxied_path.startswith('/'):
proxied_path = '/' + proxied_path
client_uri = self.get_client_uri('ws', port, proxied_path)
headers = self.request.headers
def message_cb(message):
# Websockets support both string (utf-8) and binary data, so let's
# make sure we signal that appropriately when proxying
self._record_activity()
if message is None:
self.close()
else:
self.write_message(message, binary=isinstance(message, bytes))
def ping_cb(data):
self._record_activity()
self.ping(data)
async def start_websocket_connection():
self.log.info('Trying to establish websocket connection to {}'.format(client_uri))
self._record_activity()
request = httpclient.HTTPRequest(url=client_uri, headers=headers)
self.ws = await pingable_ws_connect(request=request,
on_message_callback=message_cb, on_ping_callback=ping_cb)
self._record_activity()
self.log.info('Websocket connection established to {}'.format(client_uri))
ioloop.IOLoop.current().add_callback(start_websocket_connection)
|
async def open(self, port, proxied_path='')
|
Called when a client opens a websocket connection.
We establish a websocket connection to the proxied backend &
set up a callback to relay messages through.
| 3.427517 | 3.291242 | 1.041405 |
self._record_activity()
if hasattr(self, 'ws'):
self.ws.write_message(message, binary=isinstance(message, bytes))
|
def on_message(self, message)
|
Called when we receive a message from our client.
We proxy it to the backend.
| 6.358294 | 6.025749 | 1.055187 |
self.log.debug('jupyter_server_proxy: on_ping: {}'.format(data))
self._record_activity()
if hasattr(self, 'ws'):
self.ws.protocol.write_ping(data)
|
def on_ping(self, data)
|
Called when the client pings our websocket connection.
We proxy it to the backend.
| 7.283333 | 6.93416 | 1.050355 |
if self.proxy_base:
return url_path_join(self.base_url, self.proxy_base)
if self.absolute_url:
return url_path_join(self.base_url, 'proxy', 'absolute', str(port))
else:
return url_path_join(self.base_url, 'proxy', str(port))
|
def _get_context_path(self, port)
|
Some applications need to know where they are being proxied from.
This is either:
- {base_url}/proxy/{port}
- {base_url}/proxy/absolute/{port}
- {base_url}/{proxy_base}
| 2.928441 | 1.941724 | 1.508165 |
'''
This serverextension handles:
{base_url}/proxy/{port([0-9]+)}/{proxied_path}
{base_url}/proxy/absolute/{port([0-9]+)}/{proxied_path}
{base_url}/{proxy_base}/{proxied_path}
'''
if 'Proxy-Connection' in self.request.headers:
del self.request.headers['Proxy-Connection']
self._record_activity()
if self.request.headers.get("Upgrade", "").lower() == 'websocket':
# We wanna websocket!
# jupyterhub/jupyter-server-proxy@36b3214
self.log.info("we wanna websocket, but we don't define WebSocketProxyHandler")
self.set_status(500)
body = self.request.body
if not body:
if self.request.method == 'POST':
body = b''
else:
body = None
client = httpclient.AsyncHTTPClient()
req = self._build_proxy_request(port, proxied_path, body)
response = await client.fetch(req, raise_error=False)
# record activity at start and end of requests
self._record_activity()
# For all non http errors...
if response.error and type(response.error) is not httpclient.HTTPError:
self.set_status(500)
self.write(str(response.error))
else:
self.set_status(response.code, response.reason)
# clear tornado default header
self._headers = httputil.HTTPHeaders()
for header, v in response.headers.get_all():
if header not in ('Content-Length', 'Transfer-Encoding',
'Content-Encoding', 'Connection'):
# some header appear multiple times, eg 'Set-Cookie'
self.add_header(header, v)
if response.body:
self.write(response.body)
|
async def proxy(self, port, proxied_path)
|
This serverextension handles:
{base_url}/proxy/{port([0-9]+)}/{proxied_path}
{base_url}/proxy/absolute/{port([0-9]+)}/{proxied_path}
{base_url}/{proxy_base}/{proxied_path}
| 3.83062 | 3.054425 | 1.254122 |
'''Select a single Sec-WebSocket-Protocol during handshake.'''
if isinstance(subprotocols, list) and subprotocols:
self.log.info('Client sent subprotocols: {}'.format(subprotocols))
return subprotocols[0]
return super().select_subprotocol(subprotocols)
|
def select_subprotocol(self, subprotocols)
|
Select a single Sec-WebSocket-Protocol during handshake.
| 5.004035 | 3.731857 | 1.340897 |
if 'port' not in self.state:
sock = socket.socket()
sock.bind(('', self.requested_port))
self.state['port'] = sock.getsockname()[1]
sock.close()
return self.state['port']
|
def port(self)
|
Allocate either the requested port or a random empty port for use by
application
| 3.034498 | 2.653159 | 1.14373 |
# We don't want multiple requests trying to start the process at the same time
# FIXME: Make sure this times out properly?
# Invariant here should be: when lock isn't being held, either 'proc' is in state &
# running, or not.
with (await self.state['proc_lock']):
if 'proc' not in self.state:
# FIXME: Prevent races here
# FIXME: Handle graceful exits of spawned processes here
cmd = self.get_cmd()
server_env = os.environ.copy()
# Set up extra environment variables for process
server_env.update(self.get_env())
timeout = self.get_timeout()
proc = SupervisedProcess(self.name, *cmd, env=server_env, ready_func=self._http_ready_func, ready_timeout=timeout, log=self.log)
self.state['proc'] = proc
try:
await proc.start()
is_ready = await proc.ready()
if not is_ready:
await proc.kill()
raise web.HTTPError(500, 'could not start {} in time'.format(self.name))
except:
# Make sure we remove proc from state in any error condition
del self.state['proc']
raise
|
async def ensure_process(self)
|
Start the process
| 5.803967 | 5.732706 | 1.012431 |
'''Manage a Shiny instance.'''
name = 'shiny'
def _get_shiny_cmd(port):
conf = dedent().format(
user=getpass.getuser(),
port=str(port),
site_dir=os.getcwd()
)
f = tempfile.NamedTemporaryFile(mode='w', delete=False)
f.write(conf)
f.close()
return ['shiny-server', f.name]
return {
'command': _get_shiny_cmd,
'launcher_entry': {
'title': 'Shiny',
'icon_path': os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons', 'shiny.svg')
}
}
|
def setup_shiny()
|
Manage a Shiny instance.
| 3.053632 | 3.050564 | 1.001006 |
r
try:
requestline, _ = decode_from_bytes(data).split(CRLF, 1)
method, path, version = self._parse_requestline(requestline)
except ValueError:
try:
return self == Mocket._last_entry
except AttributeError:
return False
uri = urlsplit(path)
can_handle = uri.path == self.path and method == self.method
if self._match_querystring:
kw = dict(keep_blank_values=True)
can_handle = can_handle and parse_qs(uri.query, **kw) == parse_qs(self.query, **kw)
if can_handle:
Mocket._last_entry = self
return can_handle
|
def can_handle(self, data)
|
r"""
>>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b'<html/>'),))
>>> e.can_handle(b'GET /?bar=foo HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3 Linux/3.19.0-16-generic\r\nAccept: */*\r\n\r\n')
False
>>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b'<html/>'),))
>>> e.can_handle(b'GET /?bar=foo&foobar HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3 Linux/3.19.0-16-generic\r\nAccept: */*\r\n\r\n')
True
| 4.443664 | 4.12569 | 1.077072 |
m = re.match(r'({})\s+(.*)\s+HTTP/(1.[0|1])'.format('|'.join(Entry.METHODS)), line, re.I)
if m:
return m.group(1).upper(), m.group(2), m.group(3)
else:
raise ValueError('Not a Request-Line')
|
def _parse_requestline(line)
|
http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5
>>> Entry._parse_requestline('GET / HTTP/1.0') == ('GET', '/', '1.0')
True
>>> Entry._parse_requestline('post /testurl htTP/1.1') == ('POST', '/testurl', '1.1')
True
>>> Entry._parse_requestline('Im not a RequestLine')
Traceback (most recent call last):
...
ValueError: Not a Request-Line
| 3.819809 | 2.817626 | 1.355684 |
for n in range(1, 1024):
p = 'ns%d' % n
u = node.resolvePrefix(p, default=None)
if u is None or u == ns[1]:
return (p, ns[1])
raise Exception('auto prefix, exhausted')
|
def genprefix(cls, node, ns)
|
Generate a prefix.
@param node: An XML node on which the prefix will be used.
@type node: L{sax.element.Element}
@param ns: A namespace needing an unique prefix.
@type ns: (prefix, uri)
@return: The I{ns} with a new prefix.
| 6.723789 | 4.985097 | 1.348778 |
if not self.filter.match(root, self.ns):
return
if self.exists(root):
return
node = Element('import', ns=self.xsdns)
node.set('namespace', self.ns)
if self.location is not None:
node.set('schemaLocation', self.location)
log.debug('inserting: %s', node)
root.insert(node)
|
def apply(self, root)
|
Apply the import (rule) to the specified schema.
If the schema does not already contain an import for the
I{namespace} specified here, it is added.
@param root: A schema root.
@type root: L{Element}
| 4.277045 | 3.799808 | 1.125595 |
node = Element('import', ns=self.xsdns)
node.set('namespace', self.ns)
if self.location is not None:
node.set('schemaLocation', self.location)
log.debug('%s inserted', node)
root.insert(node)
|
def add(self, root)
|
Add an <xs:import/> to the specified schema root.
@param root: A schema root.
@type root: L{Element}
| 5.542753 | 4.706867 | 1.177589 |
for node in root.children:
if node.name != 'import':
continue
ns = node.get('namespace')
if self.ns == ns:
return 1
return 0
|
def exists(self, root)
|
Check to see if the <xs:import/> already exists
in the specified schema root by matching I{namesapce}.
@param root: A schema root.
@type root: L{Element}
| 4.790524 | 4.466196 | 1.072618 |
if result is None:
return True
reject = result in self.history
if reject:
log.debug('result %s, rejected by\n%s', Repr(result), self)
return reject
|
def filter(self, result)
|
Filter the specified result based on query criteria.
@param result: A potential result.
@type result: L{sxbase.SchemaObject}
@return: True if result should be excluded.
@rtype: boolean
| 11.29626 | 9.781245 | 1.15489 |
if result is None:
log.debug('%s, not-found', self.ref)
return
if self.resolved:
result = result.resolve()
log.debug('%s, found as: %s', self.ref, Repr(result))
self.history.append(result)
return result
|
def result(self, result)
|
Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject}
| 6.086413 | 6.471971 | 0.940427 |
for item in items:
self.unsorted.append(item)
key = item[0]
self.index[key] = item
return self
|
def add(self, *items)
|
Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList}
| 4.645621 | 5.607242 | 0.828504 |
self.sorted = list()
self.pushed = set()
for item in self.unsorted:
popped = []
self.push(item)
while len(self.stack):
try:
top = self.top()
ref = next(top[1])
refd = self.index.get(ref)
if refd is None:
log.debug('"%s" not found, skipped', Repr(ref))
continue
self.push(refd)
except StopIteration:
popped.append(self.pop())
continue
for p in popped:
self.sorted.append(p)
self.unsorted = self.sorted
return self.sorted
|
def sort(self)
|
Sort the list based on dependancies.
@return: The sorted items.
@rtype: list
| 3.987556 | 3.806861 | 1.047466 |
if item in self.pushed:
return
frame = (item, iter(item[1]))
self.stack.append(frame)
self.pushed.add(item)
|
def push(self, item)
|
Push and item onto the sorting stack.
@param item: An item to push.
@type item: I{item}
@return: The number of items pushed.
@rtype: int
| 5.467206 | 5.731687 | 0.953856 |
h = hashlib.md5(name.encode('utf8')).hexdigest()
return '%s-%s' % (h, x)
|
def mangle(self, name, x)
|
Mangle the name by hashing the I{name} and appending I{x}.
@return: the mangled name.
| 3.60277 | 3.675989 | 0.980082 |
cache = self.cache()
id = self.mangle(url, 'document')
d = cache.get(id)
if d is None:
d = self.download(url)
cache.put(id, d)
self.plugins.document.parsed(url=url, document=d.root())
return d
|
def open(self, url)
|
Open an XML document at the specified I{url}.
First, the document attempted to be retrieved from
the I{object cache}. If not found, it is downloaded and
parsed using the SAX parser. The result is added to the
cache for the next open().
@param url: A document url.
@type url: str.
@return: The specified XML document.
@rtype: I{Document}
| 5.363946 | 4.872573 | 1.100845 |
store = DocumentStore()
fp = store.open(url)
if fp is None:
fp = self.options.transport.open(Request(url))
content = fp.read()
fp.close()
ctx = self.plugins.document.loaded(url=url, document=content)
content = ctx.document
sax = Parser()
return sax.parse(string=content)
|
def download(self, url)
|
Download the docuemnt.
@param url: A document url.
@type url: str.
@return: A file pointer to the docuemnt.
@rtype: file-like
| 7.171665 | 7.483457 | 0.958336 |
cache = self.cache()
id = self.mangle(url, 'wsdl')
d = cache.get(id)
if d is None:
d = self.fn(url, self.options)
cache.put(id, d)
else:
d.options = self.options
for imp in d.imports:
imp.imported.options = self.options
return d
|
def open(self, url)
|
Open a WSDL at the specified I{url}.
First, the WSDL attempted to be retrieved from
the I{object cache}. After unpickled from the cache, the
I{options} attribute is restored.
If not found, it is downloaded and instantiated using the
I{fn} constructor and added to the cache for the next open().
@param url: A WSDL url.
@type url: str.
@return: The WSDL object.
@rtype: I{Definitions}
| 4.985515 | 3.67978 | 1.35484 |
protocol, location = self.split(url)
if protocol == self.protocol:
return self.find(location)
else:
return None
|
def open(self, url)
|
Open a document at the specified url.
@param url: A document URL.
@type url: str
@return: A file pointer to the document.
@rtype: StringIO
| 6.735348 | 8.057055 | 0.835957 |
parts = url.split('://', 1)
if len(parts) == 2:
return parts
else:
return (None, url)
|
def split(self, url)
|
Split the url into I{protocol} and I{location}
@param url: A URL.
@param url: str
@return: (I{url}, I{location})
@rtype: tuple
| 3.006131 | 2.931981 | 1.02529 |
for c in root.getChildren(ns=wsdlns):
child = Factory.create(c, self)
if child is None:
continue
self.children.append(child)
if isinstance(child, Import):
self.imports.append(child)
continue
if isinstance(child, Types):
self.types.append(child)
continue
if isinstance(child, Message):
self.messages[child.qname] = child
continue
if isinstance(child, PortType):
self.port_types[child.qname] = child
continue
if isinstance(child, Binding):
self.bindings[child.qname] = child
continue
if isinstance(child, Service):
self.services.append(child)
continue
|
def add_children(self, root)
|
Add child objects using the factory
| 2.108986 | 2.020216 | 1.043941 |
container = SchemaCollection(self)
for t in [t for t in self.types if t.local()]:
for root in t.contents():
schema = Schema(root, self.url, self.options, container)
container.add(schema)
if not len(container): # empty
root = Element.buildPath(self.root, 'types/schema')
schema = Schema(root, self.url, self.options, container)
container.add(schema)
self.schema = container.load(self.options)
for s in [t.schema() for t in self.types if t.imported()]:
self.schema.merge(s)
return self.schema
|
def build_schema(self)
|
Process L{Types} objects and create the schema collection
| 4.789182 | 4.482989 | 1.068301 |
for b in self.bindings.values():
for op in b.operations.values():
for body in (op.soap.input.body, op.soap.output.body):
body.wrapped = False
if len(body.parts) != 1:
continue
for p in body.parts:
if p.element is None:
continue
query = ElementQuery(p.element)
pt = query.execute(self.schema)
if pt is None:
raise TypeNotFound(query.ref)
resolved = pt.resolve()
if resolved.builtin():
continue
body.wrapped = True
|
def set_wrapped(self)
|
set (wrapped|bare) flag on messages
| 4.943855 | 4.843654 | 1.020687 |
url = self.location
log.debug('importing (%s)', url)
if '://' not in url:
url = urljoin(definitions.url, url)
options = definitions.options
d = Definitions(url, options)
if d.root.match(Definitions.Tag, wsdlns):
self.import_definitions(definitions, d)
return
if d.root.match(Schema.Tag, Namespace.xsdns):
self.import_schema(definitions, d)
return
raise Exception('document at "%s" is unknown' % url)
|
def load(self, definitions)
|
Load the object by opening the URL
| 5.438166 | 5.195735 | 1.04666 |
if not len(definitions.types):
types = Types.create(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
| 6.257545 | 6.171124 | 1.014004 |
s = self.root.get(a)
if s is None:
return s
else:
return qualify(s, self.root, tns)
|
def __getref(self, a, tns)
|
Get the qualified value of attribute named 'a'.
| 5.568102 | 4.512477 | 1.233935 |
for op in self.operations.values():
if op.input is None:
op.input = Message(Element('no-input'), definitions)
else:
qref = qualify(op.input, self.root, definitions.tns)
msg = definitions.messages.get(qref)
if msg is None:
raise Exception("msg '%s', not-found" % op.input)
else:
op.input = msg
if op.output is None:
op.output = Message(Element('no-output'), definitions)
else:
qref = qualify(op.output, self.root, definitions.tns)
msg = definitions.messages.get(qref)
if msg is None:
raise Exception("msg '%s', not-found" % op.output)
else:
op.output = msg
for f in op.faults:
qref = qualify(f.message, self.root, definitions.tns)
msg = definitions.messages.get(qref)
if msg is None:
raise Exception("msg '%s', not-found" % f.message)
f.message = msg
|
def resolve(self, definitions)
|
Resolve named references to other WSDL objects.
@param definitions: A definitions object.
@type definitions: L{Definitions}
| 2.240432 | 2.124937 | 1.054352 |
dsop = Element('operation', ns=soapns)
for c in root.getChildren('operation'):
op = Facade('Operation')
op.name = c.get('name')
sop = c.getChild('operation', default=dsop)
soap = Facade('soap')
soap.action = '"%s"' % sop.get('soapAction', default='')
soap.style = sop.get('style', default=self.soap.style)
soap.input = Facade('Input')
soap.input.body = Facade('Body')
soap.input.headers = []
soap.output = Facade('Output')
soap.output.body = Facade('Body')
soap.output.headers = []
op.soap = soap
input = c.getChild('input')
if input is None:
input = Element('input', ns=wsdlns)
body = input.getChild('body')
self.body(definitions, soap.input.body, body)
for header in input.getChildren('header'):
self.header(definitions, soap.input, header)
output = c.getChild('output')
if output is None:
output = Element('output', ns=wsdlns)
body = output.getChild('body')
self.body(definitions, soap.output.body, body)
for header in output.getChildren('header'):
self.header(definitions, soap.output, header)
faults = []
for fault in c.getChildren('fault'):
sf = fault.getChild('fault')
if sf is None:
continue
fn = fault.get('name')
f = Facade('Fault')
f.name = sf.get('name', default=fn)
f.use = sf.get('use', default='literal')
faults.append(f)
soap.faults = faults
self.operations[op.name] = op
|
def add_operations(self, root, definitions)
|
Add <operation/> children
| 2.280862 | 2.236436 | 1.019865 |
if root is None:
body.use = 'literal'
body.namespace = definitions.tns
body.parts = ()
return
parts = root.get('parts')
if parts is None:
body.parts = ()
else:
body.parts = re.split('[\s,]', parts)
body.use = root.get('use', default='literal')
ns = root.get('namespace')
if ns is None:
body.namespace = definitions.tns
else:
prefix = root.findPrefix(ns, 'b0')
body.namespace = (prefix, ns)
|
def body(self, definitions, body, root)
|
add the input/output body properties
| 4.046791 | 3.72307 | 1.08695 |
if root is None:
return
header = Facade('Header')
parent.headers.append(header)
header.use = root.get('use', default='literal')
ns = root.get('namespace')
if ns is None:
header.namespace = definitions.tns
else:
prefix = root.findPrefix(ns, 'h0')
header.namespace = (prefix, ns)
msg = root.get('message')
if msg is not None:
header.message = msg
part = root.get('part')
if part is not None:
header.part = part
|
def header(self, definitions, parent, root)
|
add the input/output header properties
| 4.23071 | 4.066489 | 1.040384 |
self.resolveport(definitions)
for op in self.operations.values():
self.resolvesoapbody(definitions, op)
self.resolveheaders(definitions, op)
self.resolvefaults(definitions, op)
|
def 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.133532 | 4.116981 | 1.246917 |
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)
else:
self.type = port_type
|
def resolveport(self, definitions)
|
Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions}
| 6.165906 | 5.931361 | 1.039543 |
for p in self.ports:
for m in p.methods.values():
if names is None or m.name in names:
m.location = url
|
def setlocation(self, url, names=None)
|
Override the invocation location (url) for service method.
@param url: A url location.
@type url: A url.
@param names: A list of method names. None=ALL
@type names: [str,..]
| 4.43401 | 3.704821 | 1.196821 |
if not self.escaped:
post = sax.encoder.encode(self)
escaped = post != self
return Text(post, lang=self.lang, escaped=escaped)
return self
|
def escape(self)
|
Encode (escape) special XML characters.
@return: The text with XML special characters escaped.
@rtype: L{Text}
| 11.928605 | 10.653156 | 1.119725 |
if self.escaped:
post = sax.encoder.decode(self)
return Text(post, lang=self.lang)
return self
|
def unescape(self)
|
Decode (unescape) special XML characters.
@return: The text with escaped XML special characters decoded.
@rtype: L{Text}
| 15.515299 | 13.766195 | 1.127058 |
timer = metrics.Timer()
timer.start()
sax, handler = self.saxparser()
if file is not None:
sax.parse(file)
timer.stop()
metrics.log.debug('sax (%s) duration: %s', file, timer)
return handler.nodes[0]
if string is not None:
if isinstance(string, str):
string = string.encode()
parseString(string, handler)
timer.stop()
metrics.log.debug('%s\nsax duration: %s', string, timer)
return handler.nodes[0]
|
def parse(self, file=None, string=None)
|
SAX parse XML text.
@param file: Parse a python I{file-like} object.
@type file: I{file-like} object.
@param string: Parse string XML.
@type string: str
| 3.473757 | 3.401077 | 1.02137 |
content = Content(node)
content.type = type
return Core.process(self, content)
|
def process(self, node, type)
|
Process an object graph representation of the xml L{node}.
@param node: An XML tree.
@type node: L{sax.element.Element}
@param type: The I{optional} schema type.
@type type: L{xsd.sxbase.SchemaObject}
@return: A suds object.
@rtype: L{Object}
| 11.501282 | 14.232691 | 0.808089 |
type = self.resolver.findattr(name)
if type is None:
log.warn('attribute (%s) type, not-found', name)
else:
value = self.translated(value, type)
Core.append_attribute(self, name, value, content)
|
def append_attribute(self, name, value, content)
|
Append an attribute name/value into L{Content.data}.
@param name: The attribute name
@type name: basestring
@param value: The attribute's value
@type value: basestring
@param content: The current content being unmarshalled.
@type content: L{Content}
| 7.691216 | 8.885874 | 0.865555 |
Core.append_text(self, content)
known = self.resolver.top().resolved
content.text = self.translated(content.text, known)
|
def append_text(self, content)
|
Append text nodes into L{Content.data}
Here is where the I{true} type is used to translate the value
into the proper python type.
@param content: The current content being unmarshalled.
@type content: L{Content}
| 17.844376 | 25.719315 | 0.693812 |
if value is not None:
resolved = type.resolve()
return resolved.translate(value)
else:
return value
|
def translated(self, value, type)
|
translate using the schema type
| 5.614746 | 5.070776 | 1.107276 |
log.debug('processing:\n%s', content)
self.reset()
if content.tag is None:
content.tag = content.value.__class__.__name__
document = Document()
if isinstance(content.value, Property):
root = self.node(content) # root is never used?
self.append(document, content)
else:
self.append(document, content)
return document.root()
|
def process(self, content)
|
Process (marshal) the tag with the specified value using the
optional type information.
@param content: The content to process.
@type content: L{Object}
| 5.944353 | 5.641648 | 1.053655 |
log.debug('appending parent:\n%s\ncontent:\n%s', parent, content)
if self.start(content):
self.appender.append(parent, content)
self.end(parent, content)
|
def append(self, parent, content)
|
Append the specified L{content} to the I{parent}.
@param parent: The parent node to append to.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Object}
| 4.760625 | 5.036795 | 0.94517 |
qref = self.type
if qref is None and len(self) == 0:
ls = []
m = RestrictionMatcher()
finder = NodeFinder(m, 1)
finder.find(self, ls)
if len(ls):
return ls[0].ref
return qref
|
def qref(self)
|
Get the I{type} qualified reference to the referenced xsd type.
This method takes into account simple types defined through
restriction with are detected by determining that self is simple
(len=0) and by finding a restriction child.
@return: The I{type} qualified reference.
@rtype: qref
| 6.934516 | 5.497951 | 1.261291 |
p, u = Namespace.xsdns
mp = self.root.findPrefix(u)
if mp is None:
mp = p
self.root.addPrefix(p, u)
return ':'.join((mp, 'anyType'))
|
def anytype(self)
|
create an xsd:anyType reference
| 9.848819 | 7.942863 | 1.239958 |
if location is None:
location = ns
cls.locations[ns] = location
|
def bind(cls, ns, location=None)
|
Bind a namespace to a schema location (URI).
This is used for imports that don't specify a schemaLocation.
@param ns: A namespace-uri.
@type ns: str
@param location: The (optional) schema location for the
namespace. (default=ns).
@type location: str
| 6.31362 | 5.584995 | 1.130461 |
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:
result = self.download(options)
log.debug('imported:\n%s', result)
return result
|
def open(self, options)
|
Open and import the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
| 5.94103 | 5.466836 | 1.08674 |
if self.opened:
return
self.opened = True
log.debug('%s, including location="%s"', self.id, self.location)
result = self.download(options)
log.debug('included:\n%s', result)
return result
|
def open(self, options)
|
Open and include the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
| 6.494643 | 7.152618 | 0.908009 |
url = self.location
try:
if '://' not in url:
url = urljoin(self.schema.baseurl, url)
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set('url', url)
self.__applytns(root)
return self.schema.instance(root, url, options)
except TransportError:
msg = 'include schema at (%s), failed' % url
log.error('%s, %s', self.id, msg, exc_info=True)
raise Exception(msg)
|
def download(self, options)
|
download the schema
| 6.535056 | 5.835963 | 1.11979 |
fn = cls.tags.get(root.name)
if fn is not None:
return fn(schema, root)
else:
return None
|
def create(cls, root, schema)
|
Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param schema: A schema object.
@type schema: L{schema.Schema}
@return: The created object.
@rtype: L{SchemaObject}
| 4.97934 | 4.709875 | 1.057213 |
children = []
for node in root.getChildren(ns=Namespace.xsdns):
if '*' in filter or node.name in filter:
child = cls.create(node, schema)
if child is None:
continue
children.append(child)
c = cls.build(node, schema, child.childtags())
child.rawchildren = c
return children
|
def build(cls, root, schema, filter=('*',))
|
Build an xsobject representation.
@param root: An schema XML root.
@type root: L{sax.element.Element}
@param filter: A tag filter.
@type filter: [str,...]
@return: A schema object graph.
@rtype: L{sxbase.SchemaObject}
| 5.250059 | 5.33205 | 0.984623 |
a = Attribute(self.qname(), self.value)
a.parent = parent
return a
|
def clone(self, parent=None)
|
Clone this object.
@param parent: The parent for the clone.
@type parent: L{element.Element}
@return: A copy of this object assigned to the new parent.
@rtype: L{Attribute}
| 7.906714 | 9.027187 | 0.875878 |
if isinstance(value, Text):
self.value = value
else:
self.value = Text(value)
return self
|
def setValue(self, value)
|
Set the attributes value
@param value: The new value (may be None)
@type value: basestring
@return: self
@rtype: L{Attribute}
| 3.59462 | 4.516095 | 0.795958 |
if self.prefix is None:
return Namespace.default
else:
return self.resolvePrefix(self.prefix)
|
def namespace(self)
|
Get the attributes namespace. This may either be the namespace
defined by an optional prefix, or its parent's namespace.
@return: The attribute's namespace
@rtype: (I{prefix}, I{name})
| 7.458127 | 5.411125 | 1.378295 |
ns = Namespace.default
if self.parent is not None:
ns = self.parent.resolvePrefix(prefix)
return ns
|
def resolvePrefix(self, prefix)
|
Resolve the specified prefix to a known namespace.
@param prefix: A declared prefix
@type prefix: basestring
@return: The namespace that has been mapped to I{prefix}
@rtype: (I{prefix}, I{name})
| 5.224296 | 6.584423 | 0.793433 |
if name is None:
byname = True
else:
byname = self.name == name
if ns is None:
byns = True
else:
byns = self.namespace()[1] == ns[1]
return byname and byns
|
def match(self, name=None, ns=None)
|
Match by (optional) name and/or (optional) namespace.
@param name: The optional attribute tag name.
@type name: str
@param ns: An optional namespace.
@type ns: (I{prefix}, I{name})
@return: True if matched.
@rtype: boolean
| 2.939126 | 3.005497 | 0.977917 |
appender = self.default
for a in self.appenders:
if a[0] == content.value:
appender = a[1]
break
appender.append(parent, content)
|
def append(self, parent, content)
|
Select an appender and append the content to parent.
@param parent: A parent node.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Content}
| 4.522542 | 4.191386 | 1.079009 |
aty = content.aty[1]
resolved = content.type.resolve()
array = Factory.object(resolved.name)
array.item = []
query = TypeQuery(aty)
ref = query.execute(self.schema)
if ref is None:
raise TypeNotFound(qref)
for x in content.value:
if isinstance(x, (list, tuple)):
array.item.append(x)
continue
if isinstance(x, Object):
md = x.__metadata__
md.sxtype = ref
array.item.append(x)
continue
if isinstance(x, dict):
x = Factory.object(ref.name, x)
md = x.__metadata__
md.sxtype = ref
array.item.append(x)
continue
x = Factory.property(ref.name, x)
md = x.__metadata__
md.sxtype = ref
array.item.append(x)
content.value = array
return self
|
def cast(self, content)
|
Cast the I{untyped} list items found in content I{value}.
Each items contained in the list is checked for XSD type information.
Items (values) that are I{untyped}, are replaced with suds objects and
type I{metadata} is added.
@param content: The content holding the collection.
@type content: L{Content}
@return: self
@rtype: L{Encoded}
| 3.922973 | 3.721625 | 1.054102 |
ns = method.soap.input.body.namespace
if ns[0] is None:
ns = ('ns0', ns[1])
method = Element(method.name, ns=ns)
return method
|
def method(self, method)
|
Get the document root. For I{rpc/(literal|encoded)}, this is the
name of the method qualifed by the schema tns.
@param method: A service method.
@type method: I{service.Method}
@return: A root element.
@rtype: L{Element}
| 7.642568 | 7.682882 | 0.994753 |
if typed:
return UmxEncoded(self.schema())
else:
return RPC.unmarshaller(self, typed)
|
def unmarshaller(self, typed=True)
|
Get the appropriate XML decoder.
@return: Either the (basic|typed) unmarshaller.
@rtype: L{UmxTyped}
| 19.160686 | 12.296505 | 1.558222 |
p = Unskin(self.options)
p.update(kwargs)
|
def set_options(self, **kwargs)
|
Set options.
@param kwargs: keyword arguments.
@see: L{Options}
| 27.306852 | 34.326904 | 0.795494 |
root = self.wsdl.root
mapped = root.resolvePrefix(prefix, None)
if mapped is None:
root.addPrefix(prefix, uri)
return
if mapped[1] != uri:
raise Exception('"%s" already mapped as "%s"' % (prefix, mapped))
|
def add_prefix(self, prefix, uri)
|
Add I{static} mapping of an XML namespace prefix to a namespace.
This is useful for cases when a wsdl and referenced schemas make heavy
use of namespaces and those namespaces are subject to changed.
@param prefix: An XML namespace prefix.
@type prefix: str
@param uri: An XML namespace URI.
@type uri: str
@raise Exception: when prefix is already mapped.
| 5.251902 | 4.296034 | 1.2225 |
class Uninitialized(Client):
def __init__(self):
pass
clone = Uninitialized()
clone.options = Options()
cp = Unskin(clone.options)
mp = Unskin(self.options)
cp.update(deepcopy(mp))
clone.wsdl = self.wsdl
clone.factory = self.factory
clone.service = ServiceSelector(clone, self.wsdl.services)
clone.sd = self.sd
clone.messages = dict(tx=None, rx=None)
return clone
|
def clone(self)
|
Get a shallow clone of this object.
The clone only shares the WSDL. All other attributes are
unique to the cloned object including options.
@return: A shallow clone.
@rtype: L{Client}
| 7.688814 | 5.941094 | 1.294175 |
port = None
if not len(self.__ports):
raise Exception('No ports defined: %s' % self.__qn)
if isinstance(name, int):
qn = '%s[%d]' % (self.__qn, name)
try:
port = self.__ports[name]
except IndexError:
raise PortNotFound(qn)
else:
qn = '.'.join((self.__qn, name))
for p in self.__ports:
if name == p.name:
port = p
break
if port is None:
raise PortNotFound(qn)
qn = '.'.join((self.__qn, port.name))
return MethodSelector(self.__client, port.methods, qn)
|
def __find(self, name)
|
Find a I{port} by name (string) or index (integer).
@param name: The name (or index) of a port.
@type name: (int|str)
@return: A L{MethodSelector} for the found port.
@rtype: L{MethodSelector}.
| 3.056994 | 2.659583 | 1.149426 |
dp = self.__client.options.port
if dp is None:
return None
else:
return self.__find(dp)
|
def __dp(self)
|
Get the I{default} port if defined in the I{options}.
@return: A L{MethodSelector} for the I{default} port.
@rtype: L{MethodSelector}.
| 11.329678 | 8.252796 | 1.372829 |
action = self.method.soap.action
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 or the http/https request.
@return: A dictionary of header/values.
@rtype: dict
| 4.700584 | 4.678708 | 1.004676 |
simulation = kwargs[self.injkey]
msg = simulation.get('msg')
reply = simulation.get('reply')
fault = simulation.get('fault')
if msg is None:
if reply is not None:
return self.__reply(reply, args, kwargs)
if fault is not None:
return self.__fault(fault)
raise Exception('(reply|fault) expected when msg=None')
sax = Parser()
msg = sax.parse(string=msg)
return self.send(msg)
|
def invoke(self, args, kwargs)
|
Send the required soap message to invoke the specified method
@param args: A list of args for the method invoked.
@type args: list
@param kwargs: Named (keyword) args for the method invoked.
@type kwargs: dict
@return: The result of the method invocation.
@rtype: I{builtin} or I{subclass of} L{Object}
| 5.714247 | 5.974181 | 0.95649 |
binding = self.method.binding.input
msg = binding.get_message(self.method, args, kwargs)
log.debug('inject (simulated) send message:\n%s', msg)
binding = self.method.binding.output
return self.succeeded(binding, reply)
|
def __reply(self, reply, args, kwargs)
|
simulate the reply
| 10.956902 | 10.21925 | 1.072183 |
binding = self.method.binding.output
if self.options.faults:
r, p = binding.get_fault(reply)
self.last_received(r)
return (500, p)
else:
return (500, None)
|
def __fault(self, reply)
|
simulate the (fault) reply
| 7.680113 | 7.92041 | 0.969661 |
self.start(content)
self.append_attributes(content)
self.append_children(content)
self.append_text(content)
self.end(content)
return self.postprocess(content)
|
def append(self, content)
|
Process the specified node and convert the XML document into
a I{suds} L{object}.
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: A I{append-result} tuple as: (L{Object}, I{value})
@rtype: I{append-result}
@note: This is not the proper entry point.
@see: L{process()}
| 3.899472 | 3.816533 | 1.021732 |
attributes = AttrList(content.node.attributes)
for attr in attributes.real():
name = attr.name
value = attr.value
self.append_attribute(name, value, content)
|
def append_attributes(self, content)
|
Append attribute nodes into L{Content.data}.
Attributes in the I{schema} or I{xml} namespaces are skipped.
@param content: The current content being unmarshalled.
@type content: L{Content}
| 5.664653 | 5.999497 | 0.944188 |
key = name
key = '_%s' % reserved.get(key, key)
setattr(content.data, key, value)
|
def append_attribute(self, name, value, content)
|
Append an attribute name/value into L{Content.data}.
@param name: The attribute name
@type name: basestring
@param value: The attribute's value
@type value: basestring
@param content: The current content being unmarshalled.
@type content: L{Content}
| 9.923273 | 8.63739 | 1.148874 |
if content.node.hasText():
content.text = content.node.getText()
|
def append_text(self, content)
|
Append text nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content}
| 10.365523 | 10.201211 | 1.016107 |
content.data = Factory.object(content.node.name)
|
def start(self, content)
|
Processing on I{node} has started. Build and return
the proper object.
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: A subclass of Object.
@rtype: L{Object}
| 50.985264 | 49.718143 | 1.025486 |
if isinstance(object, basestring):
if encoding is None:
return object
else:
return object.encode(encoding)
if isinstance(object, tuple):
s = ['(']
for item in object:
if isinstance(item, basestring):
s.append(item)
else:
s.append(tostr(item))
s.append(', ')
s.append(')')
return ''.join(s)
if isinstance(object, list):
s = ['[']
for item in object:
if isinstance(item, basestring):
s.append(item)
else:
s.append(tostr(item))
s.append(', ')
s.append(']')
return ''.join(s)
if isinstance(object, dict):
s = ['{']
for item in object.items():
if isinstance(item[0], basestring):
s.append(item[0])
else:
s.append(tostr(item[0]))
s.append(' = ')
if isinstance(item[1], basestring):
s.append(item[1])
else:
s.append(tostr(item[1]))
s.append(', ')
s.append('}')
return ''.join(s)
try:
return unicode(object)
except:
return str(object)
|
def tostr(object, encoding=None)
|
get a unicode safe string representation of an object
| 1.334354 | 1.335279 | 0.999308 |
ns = None
p, n = splitPrefix(ref)
if p is not None:
if not isinstance(resolvers, (list, tuple)):
resolvers = (resolvers,)
for r in resolvers:
resolved = r.resolvePrefix(p)
if resolved[1] is not None:
ns = resolved
break
if ns is None:
raise Exception('prefix (%s) not resolved' % p)
else:
ns = defns
return (n, ns[1])
|
def qualify(ref, resolvers, defns=Namespace.default)
|
Get a reference that is I{qualified} by namespace.
@param ref: A referenced schema type name.
@type ref: str
@param resolvers: A list of objects to be used to resolve types.
@type resolvers: [L{sax.element.Element},]
@param defns: An optional target namespace used to qualify references
when no prefix is specified.
@type defns: A default namespace I{tuple: (prefix,uri)} used when ref not
prefixed.
@return: A qualified reference.
@rtype: (name, namespace-uri)
| 3.087154 | 2.946819 | 1.047623 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.