signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def __init__(self, environ=None):
|
<EOL>self.environ = {} if environ is None else environ<EOL>self.environ['<STR_LIT>'] = self<EOL>
|
Wrap a WSGI environ dictionary.
|
f3828:c12:m0
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def app(self):<DEDENT>
|
raise RuntimeError('<STR_LIT>')<EOL>
|
Bottle application handling this request.
|
f3828:c12:m1
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def route(self):<DEDENT>
|
raise RuntimeError('<STR_LIT>')<EOL>
|
The bottle :class:`Route` object that matches this request.
|
f3828:c12:m2
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def url_args(self):<DEDENT>
|
raise RuntimeError('<STR_LIT>')<EOL>
|
The arguments extracted from the URL.
|
f3828:c12:m3
|
@property<EOL><INDENT>def path(self):<DEDENT>
|
return '<STR_LIT:/>' + self.environ.get('<STR_LIT>','<STR_LIT>').lstrip('<STR_LIT:/>')<EOL>
|
The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
broken clients and avoid the "empty path" edge case).
|
f3828:c12:m4
|
@property<EOL><INDENT>def method(self):<DEDENT>
|
return self.environ.get('<STR_LIT>', '<STR_LIT:GET>').upper()<EOL>
|
The ``REQUEST_METHOD`` value as an uppercase string.
|
f3828:c12:m5
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def headers(self):<DEDENT>
|
return WSGIHeaderDict(self.environ)<EOL>
|
A :class:`WSGIHeaderDict` that provides case-insensitive access to
HTTP request headers.
|
f3828:c12:m6
|
def get_header(self, name, default=None):
|
return self.headers.get(name, default)<EOL>
|
Return the value of a request header, or a given default value.
|
f3828:c12:m7
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def cookies(self):<DEDENT>
|
cookies = SimpleCookie(self.environ.get('<STR_LIT>','<STR_LIT>')).values()<EOL>if len(cookies) > self.MAX_PARAMS:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>return FormsDict((c.key, c.value) for c in cookies)<EOL>
|
Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
decoded. Use :meth:`get_cookie` if you expect signed cookies.
|
f3828:c12:m8
|
def get_cookie(self, key, default=None, secret=None):
|
value = self.cookies.get(key)<EOL>if secret and value:<EOL><INDENT>dec = cookie_decode(value, secret) <EOL>return dec[<NUM_LIT:1>] if dec and dec[<NUM_LIT:0>] == key else default<EOL><DEDENT>return value or default<EOL>
|
Return the content of a cookie. To read a `Signed Cookie`, the
`secret` must match the one used to create the cookie (see
:meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
cookie or wrong signature), return a default value.
|
f3828:c12:m9
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def query(self):<DEDENT>
|
get = self.environ['<STR_LIT>'] = FormsDict()<EOL>pairs = _parse_qsl(self.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>if len(pairs) > self.MAX_PARAMS:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>for key, value in pairs:<EOL><INDENT>get[key] = value<EOL><DEDENT>return get<EOL>
|
The :attr:`query_string` parsed into a :class:`FormsDict`. These
values are sometimes called "URL arguments" or "GET parameters", but
not to be confused with "URL wildcards" as they are provided by the
:class:`Router`.
|
f3828:c12:m10
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def forms(self):<DEDENT>
|
forms = FormsDict()<EOL>for name, item in self.POST.allitems():<EOL><INDENT>if not isinstance(item, FileUpload):<EOL><INDENT>forms[name] = item<EOL><DEDENT><DEDENT>return forms<EOL>
|
Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is returned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`.
|
f3828:c12:m11
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def params(self):<DEDENT>
|
params = FormsDict()<EOL>for key, value in self.query.allitems():<EOL><INDENT>params[key] = value<EOL><DEDENT>for key, value in self.forms.allitems():<EOL><INDENT>params[key] = value<EOL><DEDENT>return params<EOL>
|
A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`.
|
f3828:c12:m12
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def files(self):<DEDENT>
|
files = FormsDict()<EOL>for name, item in self.POST.allitems():<EOL><INDENT>if isinstance(item, FileUpload):<EOL><INDENT>files[name] = item<EOL><DEDENT><DEDENT>return files<EOL>
|
File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`.
|
f3828:c12:m13
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def json(self):<DEDENT>
|
if '<STR_LIT:application/json>' in self.environ.get('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return json_loads(self._get_body_string())<EOL><DEDENT>return None<EOL>
|
If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion.
|
f3828:c12:m14
|
def _get_body_string(self):
|
clen = self.content_length<EOL>if clen > self.MEMFILE_MAX:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>if clen < <NUM_LIT:0>: clen = self.MEMFILE_MAX + <NUM_LIT:1><EOL>data = self.body.read(clen)<EOL>if len(data) > self.MEMFILE_MAX: <EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>return data<EOL>
|
read body until content-length or MEMFILE_MAX into a string. Raise
HTTPError(413) on requests that are to large.
|
f3828:c12:m16
|
@property<EOL><INDENT>def body(self):<DEDENT>
|
self._body.seek(<NUM_LIT:0>)<EOL>return self._body<EOL>
|
The HTTP request body as a seek-able file-like object. Depending on
:attr:`MEMFILE_MAX`, this is either a temporary file or a
:class:`io.BytesIO` instance. Accessing this property for the first
time reads and replaces the ``wsgi.input`` environ variable.
Subsequent accesses just do a `seek(0)` on the file object.
|
f3828:c12:m17
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def POST(self):<DEDENT>
|
post = FormsDict()<EOL>if not self.content_type.startswith('<STR_LIT>'):<EOL><INDENT>pairs = _parse_qsl(tonat(self._get_body_string(), '<STR_LIT>'))<EOL>if len(pairs) > self.MAX_PARAMS:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>for key, value in pairs:<EOL><INDENT>post[key] = value<EOL><DEDENT>return post<EOL><DEDENT>safe_env = {'<STR_LIT>':'<STR_LIT>'} <EOL>for key in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if key in self.environ: safe_env[key] = self.environ[key]<EOL><DEDENT>args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)<EOL>if py31:<EOL><INDENT>args['<STR_LIT>'] = NCTextIOWrapper(args['<STR_LIT>'], encoding='<STR_LIT>',<EOL>newline='<STR_LIT:\n>')<EOL><DEDENT>elif py3k:<EOL><INDENT>args['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>data = cgi.FieldStorage(**args)<EOL>data = data.list or []<EOL>if len(data) > self.MAX_PARAMS:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>for item in data:<EOL><INDENT>if item.filename:<EOL><INDENT>post[item.name] = FileUpload(item.file, item.name,<EOL>item.filename, item.headers)<EOL><DEDENT>else:<EOL><INDENT>post[item.name] = item.value<EOL><DEDENT><DEDENT>return post<EOL>
|
The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads).
|
f3828:c12:m18
|
@property<EOL><INDENT>def COOKIES(self):<DEDENT>
|
depr('<STR_LIT>')<EOL>return self.cookies<EOL>
|
Alias for :attr:`cookies` (deprecated).
|
f3828:c12:m19
|
@property<EOL><INDENT>def url(self):<DEDENT>
|
return self.urlparts.geturl()<EOL>
|
The full request URI including hostname and scheme. If your app
lives behind a reverse proxy or load balancer and you get confusing
results, make sure that the ``X-Forwarded-Host`` header is set
correctly.
|
f3828:c12:m20
|
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def urlparts(self):<DEDENT>
|
env = self.environ<EOL>http = env.get('<STR_LIT>') or env.get('<STR_LIT>', '<STR_LIT:http>')<EOL>host = env.get('<STR_LIT>') or env.get('<STR_LIT>')<EOL>if not host:<EOL><INDENT>host = env.get('<STR_LIT>', '<STR_LIT:127.0.0.1>')<EOL>port = env.get('<STR_LIT>')<EOL>if port and port != ('<STR_LIT>' if http == '<STR_LIT:http>' else '<STR_LIT>'):<EOL><INDENT>host += '<STR_LIT::>' + port<EOL><DEDENT><DEDENT>path = urlquote(self.fullpath)<EOL>return UrlSplitResult(http, host, path, env.get('<STR_LIT>'), '<STR_LIT>')<EOL>
|
The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server.
|
f3828:c12:m21
|
@property<EOL><INDENT>def fullpath(self):<DEDENT>
|
return urljoin(self.script_name, self.path.lstrip('<STR_LIT:/>'))<EOL>
|
Request path including :attr:`script_name` (if present).
|
f3828:c12:m22
|
@property<EOL><INDENT>def query_string(self):<DEDENT>
|
return self.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>
|
The raw :attr:`query` part of the URL (everything in between ``?``
and ``#``) as a string.
|
f3828:c12:m23
|
@property<EOL><INDENT>def script_name(self):<DEDENT>
|
script_name = self.environ.get('<STR_LIT>', '<STR_LIT>').strip('<STR_LIT:/>')<EOL>return '<STR_LIT:/>' + script_name + '<STR_LIT:/>' if script_name else '<STR_LIT:/>'<EOL>
|
The initial portion of the URL's `path` that was removed by a higher
level (server or routing middleware) before the application was
called. This script path is returned with leading and tailing
slashes.
|
f3828:c12:m24
|
def path_shift(self, shift=<NUM_LIT:1>):
|
script = self.environ.get('<STR_LIT>','<STR_LIT:/>')<EOL>self['<STR_LIT>'], self['<STR_LIT>'] = path_shift(script, self.path, shift)<EOL>
|
Shift path segments from :attr:`path` to :attr:`script_name` and
vice versa.
:param shift: The number of path segments to shift. May be negative
to change the shift direction. (default: 1)
|
f3828:c12:m25
|
@property<EOL><INDENT>def content_length(self):<DEDENT>
|
return int(self.environ.get('<STR_LIT>') or -<NUM_LIT:1>)<EOL>
|
The request body length as an integer. The client is responsible to
set this header. Otherwise, the real length of the body is unknown
and -1 is returned. In this case, :attr:`body` will be empty.
|
f3828:c12:m26
|
@property<EOL><INDENT>def content_type(self):<DEDENT>
|
return self.environ.get('<STR_LIT>', '<STR_LIT>').lower()<EOL>
|
The Content-Type header as a lowercase-string (default: empty).
|
f3828:c12:m27
|
@property<EOL><INDENT>def is_xhr(self):<DEDENT>
|
requested_with = self.environ.get('<STR_LIT>','<STR_LIT>')<EOL>return requested_with.lower() == '<STR_LIT>'<EOL>
|
True if the request was triggered by a XMLHttpRequest. This only
works with JavaScript libraries that support the `X-Requested-With`
header (most of the popular libraries do).
|
f3828:c12:m28
|
@property<EOL><INDENT>def is_ajax(self):<DEDENT>
|
return self.is_xhr<EOL>
|
Alias for :attr:`is_xhr`. "Ajax" is not the right term.
|
f3828:c12:m29
|
@property<EOL><INDENT>def auth(self):<DEDENT>
|
basic = parse_auth(self.environ.get('<STR_LIT>','<STR_LIT>'))<EOL>if basic: return basic<EOL>ruser = self.environ.get('<STR_LIT>')<EOL>if ruser: return (ruser, None)<EOL>return None<EOL>
|
HTTP authentication data as a (user, password) tuple. This
implementation currently supports basic (not digest) authentication
only. If the authentication happened at a higher level (e.g. in the
front web-server or a middleware), the password field is None, but
the user field is looked up from the ``REMOTE_USER`` environ
variable. On any errors, None is returned.
|
f3828:c12:m30
|
@property<EOL><INDENT>def remote_route(self):<DEDENT>
|
proxy = self.environ.get('<STR_LIT>')<EOL>if proxy: return [ip.strip() for ip in proxy.split('<STR_LIT:U+002C>')]<EOL>remote = self.environ.get('<STR_LIT>')<EOL>return [remote] if remote else []<EOL>
|
A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients.
|
f3828:c12:m31
|
@property<EOL><INDENT>def remote_addr(self):<DEDENT>
|
route = self.remote_route<EOL>return route[<NUM_LIT:0>] if route else None<EOL>
|
The client IP as a string. Note that this information can be forged
by malicious clients.
|
f3828:c12:m32
|
def copy(self):
|
return Request(self.environ.copy())<EOL>
|
Return a new :class:`Request` with a shallow :attr:`environ` copy.
|
f3828:c12:m33
|
def __setitem__(self, key, value):
|
if self.environ.get('<STR_LIT>'):<EOL><INDENT>raise KeyError('<STR_LIT>')<EOL><DEDENT>self.environ[key] = value<EOL>todelete = ()<EOL>if key == '<STR_LIT>':<EOL><INDENT>todelete = ('<STR_LIT:body>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif key == '<STR_LIT>':<EOL><INDENT>todelete = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif key.startswith('<STR_LIT>'):<EOL><INDENT>todelete = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>for key in todelete:<EOL><INDENT>self.environ.pop('<STR_LIT>'+key, None)<EOL><DEDENT>
|
Change an environ value and clear all caches that depend on it.
|
f3828:c12:m40
|
def __getattr__(self, name):
|
try:<EOL><INDENT>var = self.environ['<STR_LIT>'%name]<EOL>return var.__get__(self) if hasattr(var, '<STR_LIT>') else var<EOL><DEDENT>except KeyError:<EOL><INDENT>raise AttributeError('<STR_LIT>' % name)<EOL><DEDENT>
|
Search in self.environ for additional user defined attributes.
|
f3828:c12:m42
|
def copy(self):
|
<EOL>copy = Response()<EOL>copy.status = self.status<EOL>copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())<EOL>return copy<EOL>
|
Returns a copy of self.
|
f3828:c14:m1
|
@property<EOL><INDENT>def status_line(self):<DEDENT>
|
return self._status_line<EOL>
|
The HTTP status line as a string (e.g. ``404 Not Found``).
|
f3828:c14:m4
|
@property<EOL><INDENT>def status_code(self):<DEDENT>
|
return self._status_code<EOL>
|
The HTTP status code as an integer (e.g. 404).
|
f3828:c14:m5
|
@property<EOL><INDENT>def headers(self):<DEDENT>
|
hdict = HeaderDict()<EOL>hdict.dict = self._headers<EOL>return hdict<EOL>
|
An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response headers.
|
f3828:c14:m8
|
def get_header(self, name, default=None):
|
return self._headers.get(_hkey(name), [default])[-<NUM_LIT:1>]<EOL>
|
Return the value of a previously defined header. If there is no
header with that name, return a default value.
|
f3828:c14:m13
|
def set_header(self, name, value):
|
self._headers[_hkey(name)] = [str(value)]<EOL>
|
Create a new response header, replacing any previously defined
headers with the same name.
|
f3828:c14:m14
|
def add_header(self, name, value):
|
self._headers.setdefault(_hkey(name), []).append(str(value))<EOL>
|
Add an additional response header, not removing duplicates.
|
f3828:c14:m15
|
def iter_headers(self):
|
return self.headerlist<EOL>
|
Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code.
|
f3828:c14:m16
|
@property<EOL><INDENT>def headerlist(self):<DEDENT>
|
out = []<EOL>headers = list(self._headers.items())<EOL>if '<STR_LIT:Content-Type>' not in self._headers:<EOL><INDENT>headers.append(('<STR_LIT:Content-Type>', [self.default_content_type]))<EOL><DEDENT>if self._status_code in self.bad_headers:<EOL><INDENT>bad_headers = self.bad_headers[self._status_code]<EOL>headers = [h for h in headers if h[<NUM_LIT:0>] not in bad_headers]<EOL><DEDENT>out += [(name, val) for name, vals in headers for val in vals]<EOL>if self._cookies:<EOL><INDENT>for c in self._cookies.values():<EOL><INDENT>out.append(('<STR_LIT>', c.OutputString()))<EOL><DEDENT><DEDENT>return out<EOL>
|
WSGI conform list of (header, value) tuples.
|
f3828:c14:m18
|
@property<EOL><INDENT>def charset(self, default='<STR_LIT>'):<DEDENT>
|
if '<STR_LIT>' in self.content_type:<EOL><INDENT>return self.content_type.split('<STR_LIT>')[-<NUM_LIT:1>].split('<STR_LIT:;>')[<NUM_LIT:0>].strip()<EOL><DEDENT>return default<EOL>
|
Return the charset specified in the content-type header (default: utf8).
|
f3828:c14:m19
|
@property<EOL><INDENT>def COOKIES(self):<DEDENT>
|
depr('<STR_LIT>') <EOL>if not self._cookies:<EOL><INDENT>self._cookies = SimpleCookie()<EOL><DEDENT>return self._cookies<EOL>
|
A dict-like SimpleCookie instance. This should not be used directly.
See :meth:`set_cookie`.
|
f3828:c14:m20
|
def set_cookie(self, name, value, secret=None, **options):
|
if not self._cookies:<EOL><INDENT>self._cookies = SimpleCookie()<EOL><DEDENT>if secret:<EOL><INDENT>value = touni(cookie_encode((name, value), secret))<EOL><DEDENT>elif not isinstance(value, basestring):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if len(value) > <NUM_LIT>: raise ValueError('<STR_LIT>')<EOL>self._cookies[name] = value<EOL>for key, value in options.items():<EOL><INDENT>if key == '<STR_LIT>':<EOL><INDENT>if isinstance(value, timedelta):<EOL><INDENT>value = value.seconds + value.days * <NUM_LIT> * <NUM_LIT><EOL><DEDENT><DEDENT>if key == '<STR_LIT>':<EOL><INDENT>if isinstance(value, (datedate, datetime)):<EOL><INDENT>value = value.timetuple()<EOL><DEDENT>elif isinstance(value, (int, float)):<EOL><INDENT>value = time.gmtime(value)<EOL><DEDENT>value = time.strftime("<STR_LIT>", value)<EOL><DEDENT>self._cookies[name][key.replace('<STR_LIT:_>', '<STR_LIT:->')] = value<EOL><DEDENT>
|
Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:param secret: a signature key required for signed cookies.
Additionally, this method accepts all RFC 2109 attributes that are
supported by :class:`cookie.Morsel`, including:
:param max_age: maximum age in seconds. (default: None)
:param expires: a datetime object or UNIX timestamp. (default: None)
:param domain: the domain that is allowed to read the cookie.
(default: current domain)
:param path: limits the cookie to a given path (default: current path)
:param secure: limit the cookie to HTTPS connections (default: off).
:param httponly: prevents client-side javascript to read this cookie
(default: off, requires Python 2.6 or newer).
If neither `expires` nor `max_age` is set (default), the cookie will
expire at the end of the browser session (as soon as the browser
window is closed).
Signed cookies may store any pickle-able object and are
cryptographically signed to prevent manipulation. Keep in mind that
cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see
the content) and not copy-protected (the client can restore an old
cookie). The main intention is to make pickling and unpickling
save, not to store secret information at client side.
|
f3828:c14:m21
|
def delete_cookie(self, key, **kwargs):
|
kwargs['<STR_LIT>'] = -<NUM_LIT:1><EOL>kwargs['<STR_LIT>'] = <NUM_LIT:0><EOL>self.set_cookie(key, '<STR_LIT>', **kwargs)<EOL>
|
Delete a cookie. Be sure to use the same `domain` and `path`
settings as used to create the cookie.
|
f3828:c14:m22
|
def add(self, name, func):
|
was_empty = self._empty()<EOL>self.hooks.setdefault(name, []).append(func)<EOL>if self.app and was_empty and not self._empty(): self.app.reset()<EOL>
|
Attach a callback to a hook.
|
f3828:c21:m3
|
def remove(self, name, func):
|
was_empty = self._empty()<EOL>if name in self.hooks and func in self.hooks[name]:<EOL><INDENT>self.hooks[name].remove(func)<EOL><DEDENT>if self.app and not was_empty and self._empty(): self.app.reset()<EOL>
|
Remove a callback from a hook.
|
f3828:c21:m4
|
def trigger(self, name, *a, **ka):
|
hooks = self.hooks[name]<EOL>if ka.pop('<STR_LIT>', False): hooks = hooks[::-<NUM_LIT:1>]<EOL>return [hook(*a, **ka) for hook in hooks]<EOL>
|
Trigger a hook and return a list of results.
|
f3828:c21:m5
|
def __init__(self, name, impmask):
|
self.name = name<EOL>self.impmask = impmask<EOL>self.module = sys.modules.setdefault(name, imp.new_module(name))<EOL>self.module.__dict__.update({'<STR_LIT>': __file__, '<STR_LIT>': [],<EOL>'<STR_LIT>': [], '<STR_LIT>': self})<EOL>sys.meta_path.append(self)<EOL>
|
Create a virtual package that redirects imports (see PEP 302).
|
f3828:c23:m0
|
def get(self, key, default=None, index=-<NUM_LIT:1>, type=None):
|
try:<EOL><INDENT>val = self.dict[key][index]<EOL>return type(val) if type else val<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return default<EOL>
|
Return the most recent value for a key.
:param default: The default value to be returned if the key is not
present or the type conversion fails.
:param index: An index for the list of available values.
:param type: If defined, this callable is used to cast the value
into a specific type. Exception are suppressed and result in
the default value to be returned.
|
f3828:c24:m8
|
def append(self, key, value):
|
self.dict.setdefault(key, []).append(value)<EOL>
|
Add a new value to the list of values for this key.
|
f3828:c24:m9
|
def replace(self, key, value):
|
self.dict[key] = [value]<EOL>
|
Replace the list of values with a single value.
|
f3828:c24:m10
|
def getall(self, key):
|
return self.dict.get(key) or []<EOL>
|
Return a (possibly empty) list of values for a key.
|
f3828:c24:m11
|
def decode(self, encoding=None):
|
copy = FormsDict()<EOL>enc = copy.input_encoding = encoding or self.input_encoding<EOL>copy.recode_unicode = False<EOL>for key, value in self.allitems():<EOL><INDENT>copy.append(self._fix(key, enc), self._fix(value, enc))<EOL><DEDENT>return copy<EOL>
|
Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary.
|
f3828:c25:m1
|
def getunicode(self, name, default=None, encoding=None):
|
try:<EOL><INDENT>return self._fix(self[name], encoding)<EOL><DEDENT>except (UnicodeError, KeyError):<EOL><INDENT>return default<EOL><DEDENT>
|
Return the value as a unicode string, or the default.
|
f3828:c25:m2
|
def _ekey(self, key):
|
key = key.replace('<STR_LIT:->','<STR_LIT:_>').upper()<EOL>if key in self.cgikeys:<EOL><INDENT>return key<EOL><DEDENT>return '<STR_LIT>' + key<EOL>
|
Translate header field name to CGI/WSGI environ key.
|
f3828:c27:m1
|
def raw(self, key, default=None):
|
return self.environ.get(self._ekey(key), default)<EOL>
|
Return the header value as is (may be bytes or unicode).
|
f3828:c27:m2
|
def __call__(self):
|
return self[-<NUM_LIT:1>]<EOL>
|
Return the current default application.
|
f3828:c29:m0
|
def push(self, value=None):
|
if not isinstance(value, Bottle):<EOL><INDENT>value = Bottle()<EOL><DEDENT>self.append(value)<EOL>return value<EOL>
|
Add a new :class:`Bottle` instance to the stack
|
f3828:c29:m1
|
def add_path(self, path, base=None, index=None, create=False):
|
base = os.path.abspath(os.path.dirname(base or self.base))<EOL>path = os.path.abspath(os.path.join(base, os.path.dirname(path)))<EOL>path += os.sep<EOL>if path in self.path:<EOL><INDENT>self.path.remove(path)<EOL><DEDENT>if create and not os.path.isdir(path):<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>if index is None:<EOL><INDENT>self.path.append(path)<EOL><DEDENT>else:<EOL><INDENT>self.path.insert(index, path)<EOL><DEDENT>self.cache.clear()<EOL>return os.path.exists(path)<EOL>
|
Add a new path to the list of search paths. Return False if the
path does not exist.
:param path: The new search path. Relative paths are turned into
an absolute and normalized form. If the path looks like a file
(not ending in `/`), the filename is stripped off.
:param base: Path used to absolutize relative search paths.
Defaults to :attr:`base` which defaults to ``os.getcwd()``.
:param index: Position within the list of search paths. Defaults
to last index (appends to the list).
The `base` parameter makes it easy to reference files installed
along with a python module or package::
res.add_path('./resources/', __file__)
|
f3828:c32:m1
|
def __iter__(self):
|
search = self.path[:]<EOL>while search:<EOL><INDENT>path = search.pop()<EOL>if not os.path.isdir(path): continue<EOL>for name in os.listdir(path):<EOL><INDENT>full = os.path.join(path, name)<EOL>if os.path.isdir(full): search.append(full)<EOL>else: yield full<EOL><DEDENT><DEDENT>
|
Iterate over all existing files in all registered paths.
|
f3828:c32:m2
|
def lookup(self, name):
|
if name not in self.cache or DEBUG:<EOL><INDENT>for path in self.path:<EOL><INDENT>fpath = os.path.join(path, name)<EOL>if os.path.isfile(fpath):<EOL><INDENT>if self.cachemode in ('<STR_LIT:all>', '<STR_LIT>'):<EOL><INDENT>self.cache[name] = fpath<EOL><DEDENT>return fpath<EOL><DEDENT><DEDENT>if self.cachemode == '<STR_LIT:all>':<EOL><INDENT>self.cache[name] = None<EOL><DEDENT><DEDENT>return self.cache[name]<EOL>
|
Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups.
|
f3828:c32:m3
|
def open(self, name, mode='<STR_LIT:r>', *args, **kwargs):
|
fname = self.lookup(name)<EOL>if not fname: raise IOError("<STR_LIT>" % name)<EOL>return self.opener(name, mode=mode, *args, **kwargs)<EOL>
|
Find a resource and return a file object, or raise IOError.
|
f3828:c32:m4
|
def __init__(self, fileobj, name, filename, headers=None):
|
<EOL>self.file = fileobj<EOL>self.name = name<EOL>self.raw_filename = filename<EOL>self.headers = HeaderDict(headers) if headers else HeaderDict()<EOL>
|
Wrapper for file uploads.
|
f3828:c33:m0
|
@cached_property<EOL><INDENT>def filename(self):<DEDENT>
|
from unicodedata import normalize <EOL>fname = self.raw_filename<EOL>if isinstance(fname, unicode):<EOL><INDENT>fname = normalize('<STR_LIT>', fname).encode('<STR_LIT>', '<STR_LIT:ignore>')<EOL><DEDENT>fname = fname.decode('<STR_LIT>', '<STR_LIT:ignore>')<EOL>fname = os.path.basename(fname.replace('<STR_LIT:\\>', os.path.sep))<EOL>fname = re.sub(r'<STR_LIT>', '<STR_LIT>', fname).strip().lower()<EOL>fname = re.sub(r'<STR_LIT>', '<STR_LIT:->', fname.strip('<STR_LIT:.>').strip())<EOL>return fname or '<STR_LIT>'<EOL>
|
Name of the file on the client file system, but normalized to ensure
file system compatibility (lowercase, no whitespace, no path
separators, no unsafe characters, ASCII only). An empty filename
is returned as 'empty'.
|
f3828:c33:m1
|
def save(self, destination, overwrite=False, chunk_size=<NUM_LIT:2>**<NUM_LIT:16>):
|
if isinstance(destination, basestring): <EOL><INDENT>if os.path.isdir(destination):<EOL><INDENT>destination = os.path.join(destination, self.filename)<EOL><DEDENT>if not overwrite and os.path.exists(destination):<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>with open(destination, '<STR_LIT:wb>') as fp:<EOL><INDENT>self._copy_file(fp, chunk_size)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._copy_file(destination, chunk_size)<EOL><DEDENT>
|
Save file to disk or copy its content to an open file(-like) object.
If *destination* is a directory, :attr:`filename` is added to the
path. Existing files are not overwritten by default (IOError).
:param destination: File path, directory or file(-like) object.
:param overwrite: If True, replace existing files. (default: False)
:param chunk_size: Bytes to read at a time. (default: 64kb)
|
f3828:c33:m3
|
def __init__(self, source=None, name=None, lookup=[], encoding='<STR_LIT:utf8>', **settings):
|
self.name = name<EOL>self.source = source.read() if hasattr(source, '<STR_LIT>') else source<EOL>self.filename = source.filename if hasattr(source, '<STR_LIT:filename>') else None<EOL>self.lookup = [os.path.abspath(x) for x in lookup]<EOL>self.encoding = encoding<EOL>self.settings = self.settings.copy() <EOL>self.settings.update(settings) <EOL>if not self.source and self.name:<EOL><INDENT>self.filename = self.search(self.name, self.lookup)<EOL>if not self.filename:<EOL><INDENT>raise TemplateError('<STR_LIT>' % repr(name))<EOL><DEDENT><DEDENT>if not self.source and not self.filename:<EOL><INDENT>raise TemplateError('<STR_LIT>')<EOL><DEDENT>self.prepare(**self.settings)<EOL>
|
Create a new template.
If the source parameter (str or buffer) is missing, the name argument
is used to guess a template filename. Subclasses can assume that
self.source and/or self.filename are set. Both are strings.
The lookup, encoding and settings parameters are stored as instance
variables.
The lookup parameter stores a list containing directory paths.
The encoding parameter should be used to decode byte strings or files.
The settings parameter contains a dict for engine-specific settings.
|
f3828:c55:m0
|
@classmethod<EOL><INDENT>def search(cls, name, lookup=[]):<DEDENT>
|
if not lookup:<EOL><INDENT>depr('<STR_LIT>')<EOL>lookup = ['<STR_LIT:.>']<EOL><DEDENT>if os.path.isabs(name) and os.path.isfile(name):<EOL><INDENT>depr('<STR_LIT>')<EOL>return os.path.abspath(name)<EOL><DEDENT>for spath in lookup:<EOL><INDENT>spath = os.path.abspath(spath) + os.sep<EOL>fname = os.path.abspath(os.path.join(spath, name))<EOL>if not fname.startswith(spath): continue<EOL>if os.path.isfile(fname): return fname<EOL>for ext in cls.extensions:<EOL><INDENT>if os.path.isfile('<STR_LIT>' % (fname, ext)):<EOL><INDENT>return '<STR_LIT>' % (fname, ext)<EOL><DEDENT><DEDENT><DEDENT>
|
Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit.
|
f3828:c55:m1
|
@classmethod<EOL><INDENT>def global_config(cls, key, *args):<DEDENT>
|
if args:<EOL><INDENT>cls.settings = cls.settings.copy() <EOL>cls.settings[key] = args[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return cls.settings[key]<EOL><DEDENT>
|
This reads or sets the global settings stored in class.settings.
|
f3828:c55:m2
|
def prepare(self, **options):
|
raise NotImplementedError<EOL>
|
Run preparations (parsing, caching, ...).
It should be possible to call this again to refresh a template or to
update settings.
|
f3828:c55:m3
|
def render(self, *args, **kwargs):
|
raise NotImplementedError<EOL>
|
Render the template with the specified local variables and return
a single byte or unicode string. If it is a byte string, the encoding
must match self.encoding. This method must be thread-safe!
Local variables may be provided in dictionaries (args)
or directly, as keywords (kwargs).
|
f3828:c55:m4
|
@lazy_attribute<EOL><INDENT>def re_pytokens(cls):<DEDENT>
|
return re.compile(r'''<STR_LIT>''', re.VERBOSE)<EOL>
|
This matches comments and all kinds of quoted strings but does
NOT match comments (#...) within quoted strings. (trust me)
|
f3828:c59:m0
|
@classmethod<EOL><INDENT>def split_comment(cls, code):<DEDENT>
|
if '<STR_LIT:#>' not in code: return code<EOL>subf = lambda m: '<STR_LIT>' if m.group(<NUM_LIT:0>)[<NUM_LIT:0>]=='<STR_LIT:#>' else m.group(<NUM_LIT:0>)<EOL>return re.sub(cls.re_pytokens, subf, code)<EOL>
|
Removes comments (#...) from python code.
|
f3828:c59:m2
|
def render(self, *args, **kwargs):
|
for dictarg in args: kwargs.update(dictarg)<EOL>stdout = []<EOL>self.execute(stdout, kwargs)<EOL>return '<STR_LIT>'.join(stdout)<EOL>
|
Render the template using keyword arguments as local variables.
|
f3828:c59:m7
|
def load_data(verbose=False):
|
df = pd.read_csv(STOPS_PATH, usecols=['<STR_LIT>', '<STR_LIT>'])<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % (len(df), STOPS_PATH))<EOL><DEDENT>return df<EOL>
|
Load all VBB stop names and IDs into a Pandas dataframe.
|
f3836:m0
|
def filter_data(df, filter_name, verbose=False):
|
<EOL>df = df[df.stop_name.apply(<EOL>lambda cell: filter_name.encode('<STR_LIT:utf-8>') in cell)]<EOL>if verbose:<EOL><INDENT>msg = '<STR_LIT>'<EOL>print(msg % (len(df), filter_name))<EOL><DEDENT>return df<EOL>
|
Filter certain entries with given name.
|
f3836:m1
|
def get_name_id_interactive(stop, df):
|
<EOL>df1 = df[df.stop_name.apply(lambda cell: stop.lower() in cell.lower())]<EOL>df1 = df1.sort_values(by=['<STR_LIT>'])<EOL>df1_len = len(df1)<EOL>if df1_len == <NUM_LIT:1>:<EOL><INDENT>result = {<EOL>'<STR_LIT>': df1.iloc[<NUM_LIT:0>].stop_id,<EOL>'<STR_LIT>': df1.iloc[<NUM_LIT:0>].stop_name<EOL>}<EOL>return result<EOL><DEDENT>elif df1_len > <NUM_LIT:1>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>termcolor.cprint(msg, attrs=['<STR_LIT>'])<EOL>fmt = '<STR_LIT>' % len(str(df1_len))<EOL>for i, (index, _id, stop_name) in enumerate(df1.itertuples()):<EOL><INDENT>print(fmt % (i, stop_name))<EOL><DEDENT>try:<EOL><INDENT>msg = '<STR_LIT>''<STR_LIT>' % (df1_len - <NUM_LIT:1>)<EOL>msg = termcolor.colored(msg, attrs=['<STR_LIT>'])<EOL>result = raw_input(msg)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>try:<EOL><INDENT>i = int(result)<EOL><DEDENT>except ValueError:<EOL><INDENT>msg = "<STR_LIT>" % result<EOL>termcolor.cprint(msg, '<STR_LIT>', attrs=['<STR_LIT>'])<EOL>return<EOL><DEDENT>if not <NUM_LIT:0> <= i <= df1_len - <NUM_LIT:1>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>termcolor.cprint(msg, '<STR_LIT>', attrs=['<STR_LIT>'])<EOL>return<EOL><DEDENT>result = {<EOL>'<STR_LIT>': df1.iloc[i].stop_id,<EOL>'<STR_LIT>': df1.iloc[i].stop_name<EOL>}<EOL>return result<EOL><DEDENT>
|
Return VBB/BVG ID for given stop name in given table.
Enter interactive dialog when result is not unique.
|
f3836:m2
|
def wait_time(departure, now=None):
|
now = now or datetime.datetime.now()<EOL>yn, mn, dn = now.year, now.month, now.day<EOL>hour, minute = map(int, departure.split('<STR_LIT::>'))<EOL>dt = datetime.datetime(yn, mn, dn, hour=hour, minute=minute)<EOL>delta = (dt - now).seconds<EOL>if (dt - now).days < <NUM_LIT:0>:<EOL><INDENT>delta = <NUM_LIT:0><EOL><DEDENT>if delta < <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>' % (delta // <NUM_LIT>, delta % <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>delta_hh = delta // <NUM_LIT><EOL>delta_rest = delta - delta_hh * <NUM_LIT><EOL>return '<STR_LIT>' % (delta_hh, delta_rest // <NUM_LIT>, delta_rest % <NUM_LIT>)<EOL><DEDENT>
|
Calculate waiting time until the next departure time in 'HH:MM' format.
Return time-delta (as 'MM:SS') from now until next departure time in the
future ('HH:MM') given as (year, month, day, hour, minute, seconds).
Time-deltas shorter than 60 seconds are reduced to 0.
|
f3836:m3
|
def get_next_departures(stop, filter_line=None, num_line_groups=<NUM_LIT:1>, verbose=False):
|
<EOL>url = BVG_URL_PAT % stop<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % url)<EOL><DEDENT>try:<EOL><INDENT>tables = pd.read_html(url.encode('<STR_LIT:utf-8>'))<EOL><DEDENT>except urllib.error.URLError:<EOL><INDENT>msg = '<STR_LIT>'<EOL>termcolor.cprint(msg, '<STR_LIT>', attrs=['<STR_LIT>'])<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>return []<EOL><DEDENT>table = tables[<NUM_LIT:0>]<EOL>table.columns = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % (len(table), stop))<EOL><DEDENT>table.is_copy = False <EOL>table.Departure = table.apply(<EOL>lambda row: re.sub('<STR_LIT>', '<STR_LIT>', row.Departure), axis=<NUM_LIT:1>)<EOL>table.Line = table.apply(lambda row: re.sub('<STR_LIT>', '<STR_LIT:U+0020>', row.Line), axis=<NUM_LIT:1>)<EOL>indices = []<EOL>for i in range(num_line_groups):<EOL><INDENT>try:<EOL><INDENT>indices += sorted([tab.index.values[i] <EOL>for line_dest, tab in table.groupby(['<STR_LIT>', '<STR_LIT>'])])<EOL><DEDENT>except IndexError:<EOL><INDENT>break<EOL><DEDENT><DEDENT>table = table[table.index.map(lambda x: x in indices)]<EOL>table.insert(<NUM_LIT:0>, "<STR_LIT>", table.Departure.apply(lambda dep: wait_time(dep)))<EOL>if filter_line:<EOL><INDENT>table = table[table.Line.apply(<EOL>lambda cell: filter_line.lower().encode('<STR_LIT:utf-8>') in cell.lower())]<EOL><DEDENT>return table<EOL>
|
Get all real-time departure times for given stop and return as filtered table.
Terminate if we can assume there is no connection to the internet.
|
f3836:m4
|
def show_header(**header):
|
print('<STR_LIT>' % ('<STR_LIT>', header['<STR_LIT>']))<EOL>print('<STR_LIT>' % ('<STR_LIT>', header['<STR_LIT:name>']))<EOL>print('<STR_LIT>' % ('<STR_LIT>', header.get('<STR_LIT:id>', None)))<EOL>print('<STR_LIT>')<EOL>
|
Display a HTTP-style header on the command-line.
|
f3836:m5
|
def show_table(args):
|
df = load_data(verbose=args.verbose)<EOL>df = filter_data(df, filter_name=args.filter_name, verbose=args.verbose)<EOL>stop = re.sub('<STR_LIT>', '<STR_LIT:U+0020>', args.stop)<EOL>if re.match('<STR_LIT>', stop.decode('<STR_LIT:utf-8>')):<EOL><INDENT>_id = stop<EOL>name = df[df.stop_id==int(_id)].stop_name.item()<EOL><DEDENT>else:<EOL><INDENT>result = get_name_id_interactive(stop, df)<EOL>if not result:<EOL><INDENT>return<EOL><DEDENT>name, _id = result['<STR_LIT>'], result['<STR_LIT>']<EOL><DEDENT>now = datetime.datetime.now().strftime('<STR_LIT>')<EOL>tab = get_next_departures(_id, filter_line=args.filter_line, <EOL>num_line_groups=args.num_line_groups, verbose=args.verbose)<EOL>if args.header:<EOL><INDENT>show_header(now=now, name=name, id=_id)<EOL><DEDENT>if len(tab) > <NUM_LIT:0>:<EOL><INDENT>tabl = [row[<NUM_LIT:1>:]for row in tab.itertuples()]<EOL>print(tabulate(tabl, headers=list(tab.columns),<EOL>tablefmt=args.tablefmt))<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>
|
Output table on standard out.
|
f3836:m6
|
def create_lxc(name, template='<STR_LIT>', service=None):
|
service = service or LXCService<EOL>service.create(name, template=template)<EOL>meta = LXCMeta(initial=dict(type='<STR_LIT>'))<EOL>lxc = LXC.with_meta(name, service, meta, save=True)<EOL>return lxc<EOL>
|
Factory method for the generic LXC
|
f3847:m0
|
def create_lxc_with_overlays(name, base, overlays, overlay_temp_path=None,<EOL>service=None):
|
service = service or LXCService<EOL>if not overlays:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>lxc_path = service.lxc_path()<EOL>base_path = os.path.join(lxc_path, base)<EOL>new_path = os.path.join(lxc_path, name)<EOL>if not os.path.exists(new_path):<EOL><INDENT>os.mkdir(new_path)<EOL><DEDENT>overlay_group = OverlayGroup.create(new_path, base_path, overlays)<EOL>initial_meta = dict(type='<STR_LIT>',<EOL>overlay_group=overlay_group.meta())<EOL>meta = LXCMeta(initial=initial_meta)<EOL>return LXCWithOverlays.with_meta(name, service, meta, overlay_group,<EOL>save=True)<EOL>
|
Creates an LXC using overlays.
This is a fast process in comparison to LXC.create because it does not
involve any real copying of data.
|
f3847:m1
|
def start(self):
|
if self.status == '<STR_LIT>':<EOL><INDENT>raise LXCAlreadyStarted(self.name)<EOL><DEDENT>self._service.start(self.name)<EOL>
|
Start this LXC
|
f3847:c4:m3
|
def stop(self):
|
self._service.stop(self.name)<EOL>
|
Stop this LXC
|
f3847:c4:m4
|
def destroy(self, force=False):
|
if force:<EOL><INDENT>super(UnmanagedLXC, self).destroy()<EOL><DEDENT>else:<EOL><INDENT>raise UnmanagedLXCError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>
|
UnmanagedLXC Destructor.
It requires force to be true in order to work. Otherwise it throws an
error.
|
f3847:c6:m0
|
def destroy(self):
|
self._overlay_group.destroy()<EOL>
|
Unmounts overlay and deletes it's own directory
|
f3847:c7:m3
|
def top_overlay(self):
|
return self._overlay_group.top()<EOL>
|
Returns top overlay from the overlay group
|
f3847:c7:m4
|
def list(self):
|
service = self._service<EOL>lxc_names = service.list_names()<EOL>lxc_list = []<EOL>for name in lxc_names:<EOL><INDENT>lxc = self.get(name)<EOL>lxc_list.append(lxc)<EOL><DEDENT>return lxc_list<EOL>
|
Get's all of the LXC's and creates objects for them
|
f3847:c9:m1
|
def get(self, name):
|
lxc_meta_path = self._service.lxc_path(name,<EOL>constants.LXC_META_FILENAME)<EOL>meta = LXCMeta.load_from_file(lxc_meta_path)<EOL>lxc = self._loader.load(name, meta)<EOL>return lxc<EOL>
|
Retrieves a single LXC by name
|
f3847:c9:m2
|
def meta(self):
|
mount_points = []<EOL>for overlay in self.overlays:<EOL><INDENT>mount_points.append(overlay.mount_point)<EOL><DEDENT>return [self.end_dir, self.start_dir, mount_points]<EOL>
|
Data for loading later
|
f3848:c0:m4
|
def top(self):
|
return self.overlays[-<NUM_LIT:1>]<EOL>
|
Returns top most overlay
|
f3848:c0:m5
|
@classmethod<EOL><INDENT>def load_from_file(cls, file_path):<DEDENT>
|
data = None<EOL>if os.path.exists(file_path):<EOL><INDENT>metadata_file = open(file_path)<EOL>data = json.loads(metadata_file.read())<EOL><DEDENT>return cls(initial=data)<EOL>
|
Load the meta data given a file_path or empty meta data
|
f3850:c0:m0
|
def bind(self, lxc):
|
return BoundLXCMeta.bind_to_lxc(lxc, self)<EOL>
|
Bind to an LXC
|
f3850:c0:m7
|
def bind_and_save(self, lxc):
|
bound_meta = self.bind(lxc)<EOL>bound_meta.save()<EOL>return bound_meta<EOL>
|
Binds metadata to an LXC and saves it
|
f3850:c0:m8
|
@classmethod<EOL><INDENT>def list_names(cls):<DEDENT>
|
response = subwrap.run(['<STR_LIT>'])<EOL>output = response.std_out<EOL>return map(str.strip, output.splitlines())<EOL>
|
Lists all known LXC names
|
f3852:c0:m0
|
def create(cls, *args, **kwargs):
|
container = LXC.create(*args, **kwargs)<EOL>return container<EOL>
|
Creates an LXC
|
f3852:c0:m1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.