signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def dump_cookie(key, value='<STR_LIT>', max_age=None, expires=None, path='<STR_LIT:/>',<EOL>domain=None, secure=False, httponly=False,<EOL>charset='<STR_LIT:utf-8>', sync_expires=True):
key = to_bytes(key, charset)<EOL>value = to_bytes(value, charset)<EOL>if path is not None:<EOL><INDENT>path = iri_to_uri(path, charset)<EOL><DEDENT>domain = _make_cookie_domain(domain)<EOL>if isinstance(max_age, timedelta):<EOL><INDENT>max_age = (max_age.days * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>) + max_age.seconds<EOL><DEDENT>if expires is not None:<EOL><INDENT>if not isinstance(expires, string_types):<EOL><INDENT>expires = cookie_date(expires)<EOL><DEDENT><DEDENT>elif max_age is not None and sync_expires:<EOL><INDENT>expires = to_bytes(cookie_date(time() + max_age))<EOL><DEDENT>buf = [key + b'<STR_LIT:=>' + _cookie_quote(value)]<EOL>for k, v, q in ((b'<STR_LIT>', domain, True),<EOL>(b'<STR_LIT>', expires, False,),<EOL>(b'<STR_LIT>', max_age, False),<EOL>(b'<STR_LIT>', secure, None),<EOL>(b'<STR_LIT>', httponly, None),<EOL>(b'<STR_LIT>', path, False)):<EOL><INDENT>if q is None:<EOL><INDENT>if v:<EOL><INDENT>buf.append(k)<EOL><DEDENT>continue<EOL><DEDENT>if v is None:<EOL><INDENT>continue<EOL><DEDENT>tmp = bytearray(k)<EOL>if not isinstance(v, (bytes, bytearray)):<EOL><INDENT>v = to_bytes(text_type(v), charset)<EOL><DEDENT>if q:<EOL><INDENT>v = _cookie_quote(v)<EOL><DEDENT>tmp += b'<STR_LIT:=>' + v<EOL>buf.append(bytes(tmp))<EOL><DEDENT>rv = b'<STR_LIT>'.join(buf)<EOL>if not PY2:<EOL><INDENT>rv = rv.decode('<STR_LIT>')<EOL><DEDENT>return rv<EOL>
Creates a new Set-Cookie header without the ``Set-Cookie`` prefix The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too. On Python 3 the return value of this function will be a unicode string, on Python 2 it will be a native string. In both cases the return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. If a unicode string is returned it's tunneled through latin1 as required by PEP 3333. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for unicode values. :param sync_expires: automatically set expires if max_age is defined but expires not.
f5884:m31
def is_byte_range_valid(start, stop, length):
if (start is None) != (stop is None):<EOL><INDENT>return False<EOL><DEDENT>elif start is None:<EOL><INDENT>return length is None or length >= <NUM_LIT:0><EOL><DEDENT>elif length is None:<EOL><INDENT>return <NUM_LIT:0> <= start < stop<EOL><DEDENT>elif start >= stop:<EOL><INDENT>return False<EOL><DEDENT>return <NUM_LIT:0> <= start < length<EOL>
Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7
f5884:m32
def get_content_type(mimetype, charset):
if mimetype.startswith('<STR_LIT>') ormimetype == '<STR_LIT>' or(mimetype.startswith('<STR_LIT>') and<EOL>mimetype.endswith('<STR_LIT>')):<EOL><INDENT>mimetype += '<STR_LIT>' + charset<EOL><DEDENT>return mimetype<EOL>
Return the full content type string with charset for a mimetype. If the mimetype represents text the charset will be appended as charset parameter, otherwise the mimetype is returned unchanged. :param mimetype: the mimetype to be used as content type. :param charset: the charset to be appended in case it was a text mimetype. :return: the content type.
f5886:m0
def format_string(string, context):
def lookup_arg(match):<EOL><INDENT>x = context[match.group(<NUM_LIT:1>) or match.group(<NUM_LIT:2>)]<EOL>if not isinstance(x, string_types):<EOL><INDENT>x = type(string)(x)<EOL><DEDENT>return x<EOL><DEDENT>return _format_re.sub(lookup_arg, string)<EOL>
String-template format a string: >>> format_string('$foo and ${foo}s', dict(foo=42)) '42 and 42s' This does not do any attribute lookup etc. For more advanced string formattings have a look at the `werkzeug.template` module. :param string: the format string. :param context: a dict with the variables to insert.
f5886:m1
def secure_filename(filename):
if isinstance(filename, text_type):<EOL><INDENT>from unicodedata import normalize<EOL>filename = normalize('<STR_LIT>', filename).encode('<STR_LIT:ascii>', '<STR_LIT:ignore>')<EOL>if not PY2:<EOL><INDENT>filename = filename.decode('<STR_LIT:ascii>')<EOL><DEDENT><DEDENT>for sep in os.path.sep, os.path.altsep:<EOL><INDENT>if sep:<EOL><INDENT>filename = filename.replace(sep, '<STR_LIT:U+0020>')<EOL><DEDENT><DEDENT>filename = str(_filename_ascii_strip_re.sub('<STR_LIT>', '<STR_LIT:_>'.join(<EOL>filename.split()))).strip('<STR_LIT>')<EOL>if os.name == '<STR_LIT>' and filename andfilename.split('<STR_LIT:.>')[<NUM_LIT:0>].upper() in _windows_device_files:<EOL><INDENT>filename = '<STR_LIT:_>' + filename<EOL><DEDENT>return filename<EOL>
r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows system the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you generate random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure
f5886:m2
def escape(s, quote=None):
if s is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif hasattr(s, '<STR_LIT>'):<EOL><INDENT>return text_type(s.__html__())<EOL><DEDENT>elif not isinstance(s, string_types):<EOL><INDENT>s = text_type(s)<EOL><DEDENT>if quote is not None:<EOL><INDENT>from warnings import warn<EOL>warn(DeprecationWarning('<STR_LIT>'), stacklevel=<NUM_LIT:2>)<EOL><DEDENT>s = s.replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>').replace('<STR_LIT:>>', '<STR_LIT>').replace('<STR_LIT:">', "<STR_LIT>")<EOL>return s<EOL>
Replace special characters "&", "<", ">" and (") to HTML-safe sequences. There is a special handling for `None` which escapes to an empty string. .. versionchanged:: 0.9 `quote` is now implicitly on. :param s: the string to escape. :param quote: ignored.
f5886:m3
def unescape(s):
def handle_match(m):<EOL><INDENT>name = m.group(<NUM_LIT:1>)<EOL>if name in HTMLBuilder._entities:<EOL><INDENT>return unichr(HTMLBuilder._entities[name])<EOL><DEDENT>try:<EOL><INDENT>if name[:<NUM_LIT:2>] in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return unichr(int(name[<NUM_LIT:2>:], <NUM_LIT:16>))<EOL><DEDENT>elif name.startswith('<STR_LIT:#>'):<EOL><INDENT>return unichr(int(name[<NUM_LIT:1>:]))<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>return u'<STR_LIT>'<EOL><DEDENT>return _entity_re.sub(handle_match, s)<EOL>
The reverse function of `escape`. This unescapes all the HTML entities, not only the XML entities inserted by `escape`. :param s: the string to unescape.
f5886:m4
def redirect(location, code=<NUM_LIT>):
from werkzeug.wrappers import Response<EOL>display_location = escape(location)<EOL>if isinstance(location, text_type):<EOL><INDENT>from werkzeug.urls import iri_to_uri<EOL>location = iri_to_uri(location)<EOL><DEDENT>response = Response(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(escape(location), display_location), code, mimetype='<STR_LIT>')<EOL>response.headers['<STR_LIT>'] = location<EOL>return response<EOL>
Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302.
f5886:m5
def append_slash_redirect(environ, code=<NUM_LIT>):
new_path = environ['<STR_LIT>'].strip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>query_string = environ.get('<STR_LIT>')<EOL>if query_string:<EOL><INDENT>new_path += '<STR_LIT:?>' + query_string<EOL><DEDENT>return redirect(new_path, code)<EOL>
Redirect to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already. :param environ: the WSGI environment for the request that triggers the redirect. :param code: the status code for the redirect.
f5886:m6
def import_string(import_name, silent=False):
<EOL>assert isinstance(import_name, string_types)<EOL>import_name = str(import_name)<EOL>try:<EOL><INDENT>if '<STR_LIT::>' in import_name:<EOL><INDENT>module, obj = import_name.split('<STR_LIT::>', <NUM_LIT:1>)<EOL><DEDENT>elif '<STR_LIT:.>' in import_name:<EOL><INDENT>module, obj = import_name.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return __import__(import_name)<EOL><DEDENT>if PY2 and isinstance(obj, unicode):<EOL><INDENT>obj = obj.encode('<STR_LIT:utf-8>')<EOL><DEDENT>try:<EOL><INDENT>return getattr(__import__(module, None, None, [obj]), obj)<EOL><DEDENT>except (ImportError, AttributeError):<EOL><INDENT>modname = module + '<STR_LIT:.>' + obj<EOL>__import__(modname)<EOL>return sys.modules[modname]<EOL><DEDENT><DEDENT>except ImportError as e:<EOL><INDENT>if not silent:<EOL><INDENT>reraise(<EOL>ImportStringError,<EOL>ImportStringError(import_name, e),<EOL>sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>
Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object
f5886:m7
def find_modules(import_path, include_packages=False, recursive=False):
module = import_string(import_path)<EOL>path = getattr(module, '<STR_LIT>', None)<EOL>if path is None:<EOL><INDENT>raise ValueError('<STR_LIT>' % import_path)<EOL><DEDENT>basename = module.__name__ + '<STR_LIT:.>'<EOL>for importer, modname, ispkg in pkgutil.iter_modules(path):<EOL><INDENT>modname = basename + modname<EOL>if ispkg:<EOL><INDENT>if include_packages:<EOL><INDENT>yield modname<EOL><DEDENT>if recursive:<EOL><INDENT>for item in find_modules(modname, include_packages, True):<EOL><INDENT>yield item<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>yield modname<EOL><DEDENT><DEDENT>
Find all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. :param import_name: the dotted name for the package to find child modules. :param include_packages: set to `True` if packages should be returned, too. :param recursive: set to `True` if recursion should happen. :return: generator
f5886:m8
def validate_arguments(func, args, kwargs, drop_extra=True):
parser = _parse_signature(func)<EOL>args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:<NUM_LIT:5>]<EOL>if missing:<EOL><INDENT>raise ArgumentValidationError(tuple(missing))<EOL><DEDENT>elif (extra or extra_positional) and not drop_extra:<EOL><INDENT>raise ArgumentValidationError(None, extra, extra_positional)<EOL><DEDENT>return tuple(args), kwargs<EOL>
Check if the function accepts the arguments and keyword arguments. Returns a new ``(args, kwargs)`` tuple that can safely be passed to the function without causing a `TypeError` because the function signature is incompatible. If `drop_extra` is set to `True` (which is the default) any extra positional or keyword arguments are dropped automatically. The exception raised provides three attributes: `missing` A set of argument names that the function expected but where missing. `extra` A dict of keyword arguments that the function can not handle but where provided. `extra_positional` A list of values that where given by positional argument but the function cannot accept. This can be useful for decorators that forward user submitted data to a view function:: from werkzeug.utils import ArgumentValidationError, validate_arguments def sanitize(f): def proxy(request): data = request.values.to_dict() try: args, kwargs = validate_arguments(f, (request,), data) except ArgumentValidationError: raise BadRequest('The browser failed to transmit all ' 'the data expected.') return f(*args, **kwargs) return proxy :param func: the function the validation is performed against. :param args: a tuple of positional arguments. :param kwargs: a dict of keyword arguments. :param drop_extra: set to `False` if you don't want extra arguments to be silently dropped. :return: tuple in the form ``(args, kwargs)``.
f5886:m9
def bind_arguments(func, args, kwargs):
args, kwargs, missing, extra, extra_positional,arg_spec, vararg_var, kwarg_var = _parse_signature(func)(args, kwargs)<EOL>values = {}<EOL>for (name, has_default, default), value in zip(arg_spec, args):<EOL><INDENT>values[name] = value<EOL><DEDENT>if vararg_var is not None:<EOL><INDENT>values[vararg_var] = tuple(extra_positional)<EOL><DEDENT>elif extra_positional:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if kwarg_var is not None:<EOL><INDENT>multikw = set(extra) & set([x[<NUM_LIT:0>] for x in arg_spec])<EOL>if multikw:<EOL><INDENT>raise TypeError('<STR_LIT>' +<EOL>repr(next(iter(multikw))))<EOL><DEDENT>values[kwarg_var] = extra<EOL><DEDENT>elif extra:<EOL><INDENT>raise TypeError('<STR_LIT>' +<EOL>repr(next(iter(extra))))<EOL><DEDENT>return values<EOL>
Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. :param func: the function the arguments should be bound for. :param args: tuple of positional arguments. :param kwargs: a dict of keyword arguments. :return: a :class:`dict` of bound keyword arguments.
f5886:m10
def release_local(local):
local.__release_local__()<EOL>
Releases the contents of the local for the current context. This makes it possible to use locals without a manager. Example:: >>> loc = Local() >>> loc.foo = 42 >>> release_local(loc) >>> hasattr(loc, 'foo') False With this function one can release :class:`Local` objects as well as :class:`StackLocal` objects. However it is not possible to release data held by proxies that way, one always has to retain a reference to the underlying local object in order to be able to release it. .. versionadded:: 0.6.1
f5887:m0
def __call__(self, proxy):
return LocalProxy(self, proxy)<EOL>
Create a proxy for a name.
f5887:c0:m2
def push(self, obj):
rv = getattr(self._local, '<STR_LIT>', None)<EOL>if rv is None:<EOL><INDENT>self._local.stack = rv = []<EOL><DEDENT>rv.append(obj)<EOL>return rv<EOL>
Pushes a new item to the stack
f5887:c1:m5
def pop(self):
stack = getattr(self._local, '<STR_LIT>', None)<EOL>if stack is None:<EOL><INDENT>return None<EOL><DEDENT>elif len(stack) == <NUM_LIT:1>:<EOL><INDENT>release_local(self._local)<EOL>return stack[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>return stack.pop()<EOL><DEDENT>
Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty.
f5887:c1:m6
@property<EOL><INDENT>def top(self):<DEDENT>
try:<EOL><INDENT>return self._local.stack[-<NUM_LIT:1>]<EOL><DEDENT>except (AttributeError, IndexError):<EOL><INDENT>return None<EOL><DEDENT>
The topmost item on the stack. If the stack is empty, `None` is returned.
f5887:c1:m7
def get_ident(self):
return self.ident_func()<EOL>
Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy's scoped sessions) to the Werkzeug locals. .. versionchanged:: 0.7 Yu can pass a different ident function to the local manager that will then be propagated to all the locals passed to the constructor.
f5887:c2:m1
def cleanup(self):
for local in self.locals:<EOL><INDENT>release_local(local)<EOL><DEDENT>
Manually clean up the data in the locals for this context. Call this at the end of the request or use `make_middleware()`.
f5887:c2:m2
def make_middleware(self, app):
def application(environ, start_response):<EOL><INDENT>return ClosingIterator(app(environ, start_response), self.cleanup)<EOL><DEDENT>return application<EOL>
Wrap a WSGI application so that cleaning up happens after request end.
f5887:c2:m3
def middleware(self, func):
return update_wrapper(self.make_middleware(func), func)<EOL>
Like `make_middleware` but for decorating functions. Example usage:: @manager.middleware def application(environ, start_response): ... The difference to `make_middleware` is that the function passed will have all the arguments copied from the inner application (name, docstring, module).
f5887:c2:m4
def _get_current_object(self):
if not hasattr(self.__local, '<STR_LIT>'):<EOL><INDENT>return self.__local()<EOL><DEDENT>try:<EOL><INDENT>return getattr(self.__local, self.__name__)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError('<STR_LIT>' % self.__name__)<EOL><DEDENT>
Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.
f5887:c3:m1
def _log(type, message, *args, **kwargs):
global _logger<EOL>if _logger is None:<EOL><INDENT>import logging<EOL>_logger = logging.getLogger('<STR_LIT>')<EOL>if not logging.root.handlers and _logger.level == logging.NOTSET:<EOL><INDENT>_logger.setLevel(logging.INFO)<EOL>handler = logging.StreamHandler()<EOL>_logger.addHandler(handler)<EOL><DEDENT><DEDENT>getattr(_logger, type)(message.rstrip(), *args, **kwargs)<EOL>
Log into the internal werkzeug logger.
f5888:m1
def _parse_signature(func):
if hasattr(func, '<STR_LIT>'):<EOL><INDENT>func = func.im_func<EOL><DEDENT>parse = _signature_cache.get(func)<EOL>if parse is not None:<EOL><INDENT>return parse<EOL><DEDENT>positional, vararg_var, kwarg_var, defaults = inspect.getargspec(func)<EOL>defaults = defaults or ()<EOL>arg_count = len(positional)<EOL>arguments = []<EOL>for idx, name in enumerate(positional):<EOL><INDENT>if isinstance(name, list):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>default = defaults[idx - arg_count]<EOL><DEDENT>except IndexError:<EOL><INDENT>param = (name, False, None)<EOL><DEDENT>else:<EOL><INDENT>param = (name, True, default)<EOL><DEDENT>arguments.append(param)<EOL><DEDENT>arguments = tuple(arguments)<EOL>def parse(args, kwargs):<EOL><INDENT>new_args = []<EOL>missing = []<EOL>extra = {}<EOL>for idx, (name, has_default, default) in enumerate(arguments):<EOL><INDENT>try:<EOL><INDENT>new_args.append(args[idx])<EOL><DEDENT>except IndexError:<EOL><INDENT>try:<EOL><INDENT>new_args.append(kwargs.pop(name))<EOL><DEDENT>except KeyError:<EOL><INDENT>if has_default:<EOL><INDENT>new_args.append(default)<EOL><DEDENT>else:<EOL><INDENT>missing.append(name)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if name in kwargs:<EOL><INDENT>extra[name] = kwargs.pop(name)<EOL><DEDENT><DEDENT><DEDENT>extra_positional = args[arg_count:]<EOL>if vararg_var is not None:<EOL><INDENT>new_args.extend(extra_positional)<EOL>extra_positional = ()<EOL><DEDENT>if kwargs and not kwarg_var is not None:<EOL><INDENT>extra.update(kwargs)<EOL>kwargs = {}<EOL><DEDENT>return new_args, kwargs, missing, extra, extra_positional,arguments, vararg_var, kwarg_var<EOL><DEDENT>_signature_cache[func] = parse<EOL>return parse<EOL>
Return a signature object for the function.
f5888:m2
def _date_to_unix(arg):
if isinstance(arg, datetime):<EOL><INDENT>arg = arg.utctimetuple()<EOL><DEDENT>elif isinstance(arg, (int, long, float)):<EOL><INDENT>return int(arg)<EOL><DEDENT>year, month, day, hour, minute, second = arg[:<NUM_LIT:6>]<EOL>days = date(year, month, <NUM_LIT:1>).toordinal() - _epoch_ord + day - <NUM_LIT:1><EOL>hours = days * <NUM_LIT> + hour<EOL>minutes = hours * <NUM_LIT> + minute<EOL>seconds = minutes * <NUM_LIT> + second<EOL>return seconds<EOL>
Converts a timetuple, integer or datetime object into the seconds from epoch in utc.
f5888:m3
def _cookie_parse_impl(b):
i = <NUM_LIT:0><EOL>n = len(b)<EOL>while i < n:<EOL><INDENT>match = _cookie_re.search(b + b'<STR_LIT:;>', i)<EOL>if not match:<EOL><INDENT>break<EOL><DEDENT>key = match.group('<STR_LIT:key>').strip()<EOL>value = match.group('<STR_LIT>')<EOL>i = match.end(<NUM_LIT:0>)<EOL>if key.lower() not in _cookie_params:<EOL><INDENT>yield _cookie_unquote(key), _cookie_unquote(value)<EOL><DEDENT><DEDENT>
Lowlevel cookie parsing facility that operates on bytes.
f5888:m6
def _easteregg(app=None):
def bzzzzzzz(gyver):<EOL><INDENT>import base64<EOL>import zlib<EOL>return zlib.decompress(base64.b64decode(gyver)).decode('<STR_LIT:ascii>')<EOL><DEDENT>gyver = u'<STR_LIT:\n>'.join([x + (<NUM_LIT> - len(x)) * u'<STR_LIT:U+0020>' for x in bzzzzzzz(b'''<STR_LIT>''').splitlines()])<EOL>def easteregged(environ, start_response):<EOL><INDENT>def injecting_start_response(status, headers, exc_info=None):<EOL><INDENT>headers.append(('<STR_LIT>', '<STR_LIT>'))<EOL>return start_response(status, headers, exc_info)<EOL><DEDENT>if app is not None and environ.get('<STR_LIT>') != '<STR_LIT>':<EOL><INDENT>return app(environ, injecting_start_response)<EOL><DEDENT>injecting_start_response('<STR_LIT>', [('<STR_LIT:Content-Type>', '<STR_LIT>')])<EOL>return [(u'''<STR_LIT>''' % gyver).encode('<STR_LIT>')]<EOL><DEDENT>return easteregged<EOL>
Like the name says. But who knows how it works?
f5888:m10
@classmethod<EOL><INDENT>def wrap(cls, exception, name=None):<DEDENT>
class newcls(cls, exception):<EOL><INDENT>def __init__(self, arg=None, *args, **kwargs):<EOL><INDENT>cls.__init__(self, *args, **kwargs)<EOL>exception.__init__(self, arg)<EOL><DEDENT><DEDENT>newcls.__module__ = sys._getframe(<NUM_LIT:1>).f_globals.get('<STR_LIT>')<EOL>newcls.__name__ = name or cls.__name__ + exception.__name__<EOL>return newcls<EOL>
This method returns a new subclass of the exception provided that also is a subclass of `BadRequest`.
f5890:c0:m1
@property<EOL><INDENT>def name(self):<DEDENT>
return HTTP_STATUS_CODES.get(self.code, '<STR_LIT>')<EOL>
The status name.
f5890:c0:m2
def get_description(self, environ=None):
return u'<STR_LIT>' % escape(self.description)<EOL>
Get the description.
f5890:c0:m3
def get_body(self, environ=None):
return text_type((<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>) % {<EOL>'<STR_LIT:code>': self.code,<EOL>'<STR_LIT:name>': escape(self.name),<EOL>'<STR_LIT:description>': self.get_description(environ)<EOL>})<EOL>
Get the HTML body.
f5890:c0:m4
def get_headers(self, environ=None):
return [('<STR_LIT:Content-Type>', '<STR_LIT>')]<EOL>
Get a list of headers.
f5890:c0:m5
def get_response(self, environ=None):
if self.response is not None:<EOL><INDENT>return self.response<EOL><DEDENT>if environ is not None:<EOL><INDENT>environ = _get_environ(environ)<EOL><DEDENT>headers = self.get_headers(environ)<EOL>return Response(self.get_body(environ), self.code, headers)<EOL>
Get a response object. If one was passed to the exception it's returned directly. :param environ: the optional environ for the request. This can be used to modify the response depending on how the request looked like. :return: a :class:`Response` object or a subclass thereof.
f5890:c0:m6
def __call__(self, environ, start_response):
response = self.get_response(environ)<EOL>return response(environ, start_response)<EOL>
Call the exception as WSGI application. :param environ: the WSGI environment. :param start_response: the response callable provided by the WSGI server.
f5890:c0:m7
def __init__(self, valid_methods=None, description=None):
HTTPException.__init__(self, description)<EOL>self.valid_methods = valid_methods<EOL>
Takes an optional list of valid http methods starting with werkzeug 0.3 the list will be mandatory.
f5890:c7:m0
def get(self, key, default=Empty, creator=Empty, expire=None):
try:<EOL><INDENT>return self.storage.get(key)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>if creator is not Empty:<EOL><INDENT>if callable(creator):<EOL><INDENT>v = creator()<EOL><DEDENT>else:<EOL><INDENT>v = creator<EOL><DEDENT>self.set(key, v, expire)<EOL>return v<EOL><DEDENT>else:<EOL><INDENT>if default is not Empty:<EOL><INDENT>if callable(default):<EOL><INDENT>v = default()<EOL>return v<EOL><DEDENT>return default<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>
:para default: if default is callable then invoke it, save it and return it
f5891:c4:m3
def __init__(self, cache_manager, options):
BaseStorage.__init__(self, cache_manager, options)<EOL>if not options.get('<STR_LIT>'):<EOL><INDENT>options['<STR_LIT>'] = ['<STR_LIT>']<EOL><DEDENT>self.client = self.import_preferred_memcache_lib(options)<EOL>if self.client is None:<EOL><INDENT>raise Error('<STR_LIT>')<EOL><DEDENT>
options = connection = ['localhost:11211'] module = None
f5893:c1:m0
def get(self, key):
if isinstance(key, unicode):<EOL><INDENT>key = key.encode('<STR_LIT:utf-8>')<EOL><DEDENT>v = self.client.get(key)<EOL>if v is None:<EOL><INDENT>raise KeyError("<STR_LIT>" % key)<EOL><DEDENT>else:<EOL><INDENT>return v<EOL><DEDENT>
because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception
f5893:c1:m1
def __init__(self, cache_manager, options):
BaseStorage.__init__(self, cache_manager, options)<EOL>self._type = (int, long)<EOL>if '<STR_LIT>' in options:<EOL><INDENT>self.client = redis.Redis(unix_socket_path=options['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>global __connection_pool__<EOL>if not __connection_pool__ or __connection_pool__[<NUM_LIT:0>] != options['<STR_LIT>']:<EOL><INDENT>d = {'<STR_LIT:host>':'<STR_LIT:localhost>', '<STR_LIT:port>':<NUM_LIT>}<EOL>d.update(options['<STR_LIT>'])<EOL>__connection_pool__ = (d, redis.ConnectionPool(**d))<EOL><DEDENT>self.client = redis.Redis(connection_pool=__connection_pool__[<NUM_LIT:1>])<EOL><DEDENT>
options = unix_socket_path = '/tmp/redis.sock' or connection_pool = {'host':'localhost', 'port':6379, 'db':0}
f5895:c0:m0
def __init__(self, key=None, storage_type='<STR_LIT:file>', options=None, expiry_time=<NUM_LIT>*<NUM_LIT>*<NUM_LIT>,<EOL>serial_cls=None, prefix='<STR_LIT>'):
dict.__init__(self)<EOL>self._old_value = {}<EOL>self._storage_type = storage_type<EOL>self._options = options or {}<EOL>self._storage_cls = self.__get_storage()<EOL>self._storage = None<EOL>self._accessed_time = None<EOL>self.expiry_time = expiry_time<EOL>self.key = key<EOL>self.deleted = False<EOL>self.cookie = SessionCookie(self)<EOL>self._serial_cls = serial_cls or Serial<EOL>self.serial_obj = self._serial_cls()<EOL>self.prefix = prefix<EOL>self.load(self.key)<EOL>
expiry_time is just like max_age, the unit is second
f5898:c3:m0
def _make_cssmin(python_only=False):
<EOL>if not python_only:<EOL><INDENT>try:<EOL><INDENT>import _rcssmin<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return _rcssmin.cssmin<EOL><DEDENT><DEDENT>nl = r'<STR_LIT>' <EOL>spacechar = r'<STR_LIT>'<EOL>unicoded = r'<STR_LIT>'<EOL>escaped = r'<STR_LIT>'<EOL>escape = r'<STR_LIT>' % locals()<EOL>nmchar = r'<STR_LIT>'<EOL>comment = r'<STR_LIT>'<EOL>_bang_comment = r'<STR_LIT>'<EOL>string1 =r'<STR_LIT>'<EOL>string2 = r'<STR_LIT>'<EOL>strings = r'<STR_LIT>' % (string1, string2)<EOL>nl_string1 =r'<STR_LIT>'<EOL>nl_string2 = r'<STR_LIT>'<EOL>nl_strings = r'<STR_LIT>' % (nl_string1, nl_string2)<EOL>uri_nl_string1 = r'<STR_LIT>'<EOL>uri_nl_string2 = r'<STR_LIT>'<EOL>uri_nl_strings = r'<STR_LIT>' % (uri_nl_string1, uri_nl_string2)<EOL>nl_escaped = r'<STR_LIT>' % locals()<EOL>space = r'<STR_LIT>' % locals()<EOL>ie7hack = r'<STR_LIT>'<EOL>uri = (r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT:)>') % locals()<EOL>nl_unesc_sub = _re.compile(nl_escaped).sub<EOL>uri_space_sub = _re.compile((<EOL>r'<STR_LIT>'<EOL>) % locals()).sub<EOL>uri_space_subber = lambda m: m.groups()[<NUM_LIT:0>] or '<STR_LIT>'<EOL>space_sub_simple = _re.compile((<EOL>r'<STR_LIT>'<EOL>) % locals()).sub<EOL>space_sub_banged = _re.compile((<EOL>r'<STR_LIT>'<EOL>) % locals()).sub<EOL>post_esc_sub = _re.compile(r'<STR_LIT>').sub<EOL>main_sub = _re.compile((<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>) % locals()).sub<EOL>def main_subber(keep_bang_comments, base_dir='<STR_LIT>'):<EOL><INDENT>"""<STR_LIT>"""<EOL>in_macie5, in_rule, at_media = [<NUM_LIT:0>], [<NUM_LIT:0>], [<NUM_LIT:0>]<EOL>if keep_bang_comments:<EOL><INDENT>space_sub = space_sub_banged<EOL>def space_subber(match):<EOL><INDENT>"""<STR_LIT>"""<EOL>if match.lastindex:<EOL><INDENT>group1, group2 = match.group(<NUM_LIT:1>, <NUM_LIT:2>)<EOL>if group2:<EOL><INDENT>if group1.endswith(r'<STR_LIT>'):<EOL><INDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:0><EOL><DEDENT>return group1<EOL><DEDENT>elif group1:<EOL><INDENT>if group1.endswith(r'<STR_LIT>'):<EOL><INDENT>if in_macie5[<NUM_LIT:0>]:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:1><EOL>return r'<STR_LIT>'<EOL><DEDENT>elif in_macie5[<NUM_LIT:0>]:<EOL><INDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:0><EOL>return '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>space_sub = space_sub_simple<EOL>def space_subber(match):<EOL><INDENT>"""<STR_LIT>"""<EOL>if match.lastindex:<EOL><INDENT>if match.group(<NUM_LIT:1>).endswith(r'<STR_LIT>'):<EOL><INDENT>if in_macie5[<NUM_LIT:0>]:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:1><EOL>return r'<STR_LIT>'<EOL><DEDENT>elif in_macie5[<NUM_LIT:0>]:<EOL><INDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:0><EOL>return '<STR_LIT>'<EOL><DEDENT><DEDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>def fn_space_post(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>if group(<NUM_LIT:5>) is None or (<EOL>group(<NUM_LIT:6>) == '<STR_LIT::>' and not in_rule[<NUM_LIT:0>] and not at_media[<NUM_LIT:0>]):<EOL><INDENT>return '<STR_LIT:U+0020>' + space_sub(space_subber, group(<NUM_LIT:4>))<EOL><DEDENT>return space_sub(space_subber, group(<NUM_LIT:4>))<EOL><DEDENT>def fn_semicolon(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>return '<STR_LIT:;>' + space_sub(space_subber, group(<NUM_LIT:7>))<EOL><DEDENT>def fn_semicolon2(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>if in_rule[<NUM_LIT:0>]:<EOL><INDENT>return space_sub(space_subber, group(<NUM_LIT:7>))<EOL><DEDENT>return '<STR_LIT:;>' + space_sub(space_subber, group(<NUM_LIT:7>))<EOL><DEDENT>def fn_open(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>if at_media[<NUM_LIT:0>]:<EOL><INDENT>at_media[<NUM_LIT:0>] -= <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>in_rule[<NUM_LIT:0>] = <NUM_LIT:1><EOL><DEDENT>return '<STR_LIT:{>'<EOL><DEDENT>def fn_close(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>in_rule[<NUM_LIT:0>] = <NUM_LIT:0><EOL>return '<STR_LIT:}>'<EOL><DEDENT>def fn_media(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>at_media[<NUM_LIT:0>] += <NUM_LIT:1><EOL>return group(<NUM_LIT>)<EOL><DEDENT>def fn_ie7hack(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not in_rule[<NUM_LIT:0>] and not at_media[<NUM_LIT:0>]:<EOL><INDENT>in_macie5[<NUM_LIT:0>] = <NUM_LIT:0><EOL>return group(<NUM_LIT>) + space_sub(space_subber, group(<NUM_LIT:15>))<EOL><DEDENT>return '<STR_LIT:>>' + space_sub(space_subber, group(<NUM_LIT:15>))<EOL><DEDENT>def fn_url(group):<EOL><INDENT>"""<STR_LIT>"""<EOL>import os<EOL>url = uri_space_sub(uri_space_subber, group(<NUM_LIT:12>))<EOL>if base_dir:<EOL><INDENT>if (url.startswith('<STR_LIT:">') and url.endswith('<STR_LIT:">')) or (url.startswith("<STR_LIT:'>") and url.endswith("<STR_LIT:'>")):<EOL><INDENT>url = url[<NUM_LIT:0>] + os.path.join(base_dir, url[<NUM_LIT:1>:-<NUM_LIT:1>]).replace('<STR_LIT:\\>', '<STR_LIT:/>') + url[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>url = os.path.join(base_dir, url).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT><DEDENT>return '<STR_LIT>' % url<EOL><DEDENT>table = (<EOL>None,<EOL>None,<EOL>None,<EOL>None,<EOL>fn_space_post, <EOL>fn_space_post, <EOL>fn_space_post, <EOL>fn_semicolon, <EOL>fn_semicolon2, <EOL>fn_open, <EOL>fn_close, <EOL>lambda g: g(<NUM_LIT:11>), <EOL>lambda g: '<STR_LIT>' % uri_space_sub(uri_space_subber, g(<NUM_LIT:12>)),<EOL>fn_url,<EOL>fn_media, <EOL>None,<EOL>fn_ie7hack, <EOL>None,<EOL>lambda g: g(<NUM_LIT:16>) + '<STR_LIT:U+0020>' + space_sub(space_subber, g(<NUM_LIT>)),<EOL>lambda g: nl_unesc_sub('<STR_LIT>', g(<NUM_LIT>)), <EOL>lambda g: post_esc_sub('<STR_LIT:U+0020>', g(<NUM_LIT>)), <EOL>)<EOL>def func(match):<EOL><INDENT>"""<STR_LIT>"""<EOL>idx, group = match.lastindex, match.group<EOL>if idx > <NUM_LIT:3>:<EOL><INDENT>return table[idx](group)<EOL><DEDENT>elif idx == <NUM_LIT:1>: <EOL><INDENT>return group(<NUM_LIT:1>)<EOL><DEDENT>return space_sub(space_subber, group(idx))<EOL><DEDENT>return func<EOL><DEDENT>def cssmin(style, keep_bang_comments=False, base_dir='<STR_LIT>'): <EOL><INDENT>"""<STR_LIT>"""<EOL>return main_sub(main_subber(keep_bang_comments, base_dir), style)<EOL><DEDENT>return cssmin<EOL>
Generate CSS minifier. :Parameters: `python_only` : ``bool`` Use only the python variant. If true, the c extension is not even tried to be loaded. :Return: Minifier :Rtype: ``callable``
f5899:m0
def make_application(debug=None, apps_dir='<STR_LIT>', project_dir=None,<EOL>include_apps=None, debug_console=True, settings_file=None,<EOL>local_settings_file=None, start=True, default_settings=None,<EOL>dispatcher_cls=None, dispatcher_kwargs=None, debug_cls=None, debug_kwargs=None,<EOL>reuse=True, verbose=False, pythonpath=None, trace_print=False):
from uliweb.utils.common import import_attr<EOL>from uliweb.utils.whocallme import print_frame<EOL>from werkzeug.debug import DebuggedApplication<EOL>if reuse and hasattr(SimpleFrame.__global__, '<STR_LIT>') and SimpleFrame.__global__.application:<EOL><INDENT>return SimpleFrame.__global__.application<EOL><DEDENT>settings_file = settings_file or os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>local_settings_file = local_settings_file or os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>dispatcher_cls = dispatcher_cls or SimpleFrame.Dispatcher<EOL>dispatcher_kwargs = dispatcher_kwargs or {}<EOL>if project_dir:<EOL><INDENT>apps_dir = os.path.abspath(os.path.normpath(os.path.join(project_dir, '<STR_LIT>')))<EOL><DEDENT>if not project_dir:<EOL><INDENT>project_dir = os.path.abspath(os.path.normpath(os.path.abspath(os.path.join(apps_dir, '<STR_LIT:..>'))))<EOL><DEDENT>if pythonpath:<EOL><INDENT>if isinstance(pythonpath, str):<EOL><INDENT>pythonpath = pythonpath.split('<STR_LIT:;>')<EOL><DEDENT>for x in pythonpath:<EOL><INDENT>if x not in sys.path:<EOL><INDENT>sys.path.insert(<NUM_LIT:0>, x)<EOL><DEDENT><DEDENT><DEDENT>if project_dir not in sys.path:<EOL><INDENT>sys.path.insert(<NUM_LIT:0>, project_dir)<EOL><DEDENT>if apps_dir not in sys.path:<EOL><INDENT>sys.path.insert(<NUM_LIT:0>, apps_dir)<EOL><DEDENT>install_config(apps_dir)<EOL>if trace_print:<EOL><INDENT>output = sys.stdout<EOL>class MyOut(object):<EOL><INDENT>def write(self, s):<EOL><INDENT>output.write(s)<EOL>output.write('<STR_LIT:\n>')<EOL>print_frame(output)<EOL>if hasattr(output, '<STR_LIT>'):<EOL><INDENT>output.flush()<EOL><DEDENT><DEDENT><DEDENT>sys.stdout = MyOut()<EOL><DEDENT>application = app = dispatcher_cls(apps_dir=apps_dir,<EOL>include_apps=include_apps,<EOL>settings_file=settings_file,<EOL>local_settings_file=local_settings_file,<EOL>start=start,<EOL>default_settings=default_settings,<EOL>reset=True,<EOL>**dispatcher_kwargs)<EOL>if verbose:<EOL><INDENT>log.info('<STR_LIT>' % settings_file)<EOL>log.info('<STR_LIT>' % local_settings_file)<EOL><DEDENT>SimpleFrame.__global__.application = app<EOL>middlewares = []<EOL>parameters = {}<EOL>for name, v in uliweb.settings.get('<STR_LIT>', {}).items():<EOL><INDENT>order, kwargs = <NUM_LIT>, {}<EOL>if not v:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(v, (list, tuple)):<EOL><INDENT>if len(v) > <NUM_LIT:3>:<EOL><INDENT>logging.error('<STR_LIT>' % name)<EOL>raise uliweb.UliwebError('<STR_LIT>' % name)<EOL><DEDENT>cls = v[<NUM_LIT:0>]<EOL>if len(v) == <NUM_LIT:2>:<EOL><INDENT>if isinstance(v[<NUM_LIT:1>], int):<EOL><INDENT>order = v[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>kwargs = v[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>order, kwargs = v[<NUM_LIT:1>], v[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cls = v<EOL><DEDENT>middlewares.append((order, name))<EOL>parameters[name] = cls, kwargs<EOL><DEDENT>middlewares.sort(cmp=lambda x, y: cmp(x[<NUM_LIT:0>], y[<NUM_LIT:0>]))<EOL>for name in reversed([x[<NUM_LIT:1>] for x in middlewares]):<EOL><INDENT>clspath, kwargs = parameters[name]<EOL>cls = import_attr(clspath)<EOL>app = cls(app, **kwargs)<EOL><DEDENT>debug_flag = uliweb.settings.GLOBAL.DEBUG<EOL>if debug or (debug is None and debug_flag):<EOL><INDENT>if not debug_cls:<EOL><INDENT>debug_cls = DebuggedApplication<EOL><DEDENT>log.setLevel(logging.DEBUG)<EOL>log.info('<STR_LIT>')<EOL>app.debug = True<EOL>app = debug_cls(app, uliweb.settings.GLOBAL.get('<STR_LIT>', False))<EOL><DEDENT>return app<EOL>
Make an application object
f5900:m3
def interact(self, banner=None, call=None):
try:<EOL><INDENT>sys.ps1<EOL><DEDENT>except AttributeError:<EOL><INDENT>sys.ps1 = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>sys.ps2<EOL><DEDENT>except AttributeError:<EOL><INDENT>sys.ps2 = "<STR_LIT>"<EOL><DEDENT>cprt = '<STR_LIT>'<EOL>if banner is None:<EOL><INDENT>self.write("<STR_LIT>" %<EOL>(sys.version, sys.platform, cprt,<EOL>self.__class__.__name__))<EOL><DEDENT>else:<EOL><INDENT>self.write("<STR_LIT>" % str(banner))<EOL><DEDENT>more = <NUM_LIT:0><EOL>if call:<EOL><INDENT>call()<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>if more:<EOL><INDENT>prompt = sys.ps2<EOL><DEDENT>else:<EOL><INDENT>prompt = sys.ps1<EOL><DEDENT>try:<EOL><INDENT>line = self.raw_input(prompt)<EOL>encoding = getattr(sys.stdin, "<STR_LIT>", None)<EOL>if encoding and not isinstance(line, str):<EOL><INDENT>line = line.decode(encoding)<EOL><DEDENT><DEDENT>except EOFError:<EOL><INDENT>self.write("<STR_LIT:\n>")<EOL>break<EOL><DEDENT>else:<EOL><INDENT>more = self.push(line)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>self.write("<STR_LIT>")<EOL>self.resetbuffer()<EOL>more = <NUM_LIT:0><EOL><DEDENT><DEDENT>
Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!).
f5900:c15:m0
def _find_template(self, template, tree, blocks, with_filename,<EOL>source, comment):
from uliweb import application<EOL>from uliweb.core.template import _format_code<EOL>def get_rel_filename(filename, path):<EOL><INDENT>f1 = os.path.splitdrive(filename)[<NUM_LIT:1>]<EOL>f2 = os.path.splitdrive(path)[<NUM_LIT:1>]<EOL>f = os.path.relpath(f1, f2).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL>if f.startswith('<STR_LIT:..>'):<EOL><INDENT>return filename.replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT>else:<EOL><INDENT>return f<EOL><DEDENT><DEDENT>template_file = None<EOL>if not tree:<EOL><INDENT>application.template_loader.comment = comment<EOL>files = application.template_loader.find_templates(template)<EOL>if files:<EOL><INDENT>template_file = files[<NUM_LIT:0>]<EOL>for x in files:<EOL><INDENT>print(x)<EOL><DEDENT>if source:<EOL><INDENT>print()<EOL>print('<STR_LIT>' % template)<EOL>t = application.template_loader.load(template_file)<EOL>if t and comment:<EOL><INDENT>print(_format_code(t.code).rstrip())<EOL>print()<EOL><DEDENT>else:<EOL><INDENT>print(t.code)<EOL>print()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>application.template_loader.print_tree(template)<EOL><DEDENT>if template_file and blocks:<EOL><INDENT>application.template_loader.print_blocks(template, with_filename)<EOL><DEDENT>
If tree is true, then will display the track of template extend or include
f5900:c17:m3
def _validate_templates(self, app, files, verbose):
from uliweb import application<EOL>from uliweb.core.template import template_file<EOL>from uliweb.utils.common import trim_path<EOL>app.template_loader.log = None<EOL>for f in files:<EOL><INDENT>try:<EOL><INDENT>t = app.template_loader.load(f)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>', f)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>print('<STR_LIT>', f, str(e))<EOL><DEDENT><DEDENT>
If tree is true, then will display the track of template extend or include
f5900:c18:m2
@iface.property<EOL><INDENT>def time(self) -> typing.Union[int, float]:<DEDENT>
raise NotImplementedError()<EOL>
Get the current processor time. The time must always be returned as a numeric value that represents seconds.
f5901:c0:m0
@iface.method<EOL><INDENT>def defer(<EOL>self,<EOL>func: typing.Callable[[], typing.Any],<EOL>until: typing.Union[int, float]=-<NUM_LIT:1>,<EOL>) -> typing.Any:<DEDENT>
raise NotImplementedError()<EOL>
Defer the execution of a function until some clock value. Args: func (typing.Callable[[], typing.Any]): A callable that accepts no arguments. All return values are ignored. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: typing.Any: An opaque identifier that represents the callback uniquely within the processor. This identifier is used to modify the callback scheduling. Note: The time given should not be considered absolute. It represents the time when the callback becomes available to execute. It may be much later than the given time value when the function actually executes depending on the implementation.
f5901:c0:m1
@iface.method<EOL><INDENT>def defer_for(<EOL>self,<EOL>wait: typing.Union[int, float],<EOL>func: typing.Callable[[], typing.Any],<EOL>) -> typing.Any:<DEDENT>
raise NotImplementedError()<EOL>
Defer the execution of a function for some number of seconds. Args: wait (typing.Union[int, float]): A numeric value that represents the number of seconds that must pass before the callback becomes available for execution. All given values must be positive. func (typing.Callable[[], typing.Any]): A callable that accepts no arguments. All return values are ignored. Returns: typing.Any: An opaque identifier that represents the callback uniquely within the processor. This identifier is used to modify the callback scheduling.
f5901:c0:m2
@iface.method<EOL><INDENT>def delay(<EOL>self,<EOL>identifier: typing.Any,<EOL>until: typing.Union[int, float]=-<NUM_LIT:1>,<EOL>) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Delay a deferred function until the given time. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. until (typing.Union[int, float]): A numeric value that represents the clock time when the callback becomes available for execution. Values that are less than the current time result in the function being called at the next opportunity. Returns: bool: True if the call is delayed. False if the identifier is invalid or if the deferred call is already executed.
f5901:c0:m3
@iface.method<EOL><INDENT>def delay_for(<EOL>self,<EOL>wait: typing.Union[int, float],<EOL>identifier: typing.Any,<EOL>) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Defer the execution of a function for some number of seconds. Args: wait (typing.Union[int, float]): A numeric value that represents the number of seconds that must pass before the callback becomes available for execution. All given values must be positive. identifier (typing.Any): The identifier returned from a call to defer or defer_for. Returns: bool: True if the call is delayed. False if the identifier is invalid or if the deferred call is already executed.
f5901:c0:m4
@iface.method<EOL><INDENT>def cancel(self, identifier: typing.Any) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Cancel a deferred function call. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. Returns: bool: True if the call is cancelled. False if the identifier is invalid or if the deferred call is already executed.
f5901:c0:m5
@iface.method<EOL><INDENT>def pending(self, identifier: typing.Any) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Get the pending status of a deferred function call. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. Returns: bool: True if the call is pending. False if the identifier is invalid or if the deferred call is executed.
f5901:c0:m6
@iface.method<EOL><INDENT>def __call__(self) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Enact the processor for one step. All processors must be a callable that accept zero arguments.
f5903:c0:m0
@iface.method<EOL><INDENT>def handle_exception(self) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Handle any uncaught exceptions that are raised by the Processor. This method will always be called from within an except block.
f5903:c0:m1
@iface.method<EOL><INDENT>def fileno(self) -> int:<DEDENT>
raise NotImplementedError()<EOL>
Return an integer file descripter for the object.
f5904:c0:m0
@iface.method<EOL><INDENT>def add_reader(<EOL>self,<EOL>fd: IFileLike,<EOL>callback: typing.Callable[[IFileLike], typing.Any],<EOL>) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Add a file descriptor to the processor and wait for READ. Args: fd (IFileLike): Any obect that exposes a 'fileno' method that returns a valid file descriptor integer. callback (typing.Callable[[IFileLike], typing.Any]): A function that consumes the IFileLike object whenever the READ event is fired.
f5904:c1:m0
@iface.method<EOL><INDENT>def remove_reader(self, fd: IFileLike) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Remove a file descriptor waiting for READ from the processor. Args: fd (IFileLike): Any obect that exposes a 'fileno' method that returns a valid file descriptor integer. Returns: bool: True if the reader was removed. False if it was not in the processor.
f5904:c1:m1
@iface.method<EOL><INDENT>def add_writer(<EOL>self,<EOL>fd: IFileLike,<EOL>callback: typing.Callable[[IFileLike], typing.Any],<EOL>) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Add a file descriptor to the processor and wait for WRITE. Args: fd (IFileLike): Any obect that exposes a 'fileno' method that returns a valid file descriptor integer. callback (typing.Callable[[IFileLike], typing.Any]): A function that consumes the IFileLike object whenever the WRITE event is fired.
f5904:c1:m2
@iface.method<EOL><INDENT>def remove_writer(self, fd: IFileLike) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Remove a file descriptor waiting for WRITE from the processor. Args: fd (IFileLike): Any obect that exposes a 'fileno' method that returns a valid file descriptor integer. Returns: bool: True if the reader was removed. False if it was not in the processor.
f5904:c1:m3
@iface.attribute<EOL><INDENT>def processors(self) -> typing.Iterable[iprocessor.IProcessor]:<DEDENT>
raise NotImplementedError()<EOL>
Get an iterable of all processors attached to the engine.
f5905:c0:m0
@iface.attribute<EOL><INDENT>def running(self) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Get whether the engine is currently running or not.
f5905:c0:m1
@iface.method<EOL><INDENT>def start(self) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Start the engine and run it until stopped.
f5905:c0:m2
@iface.method<EOL><INDENT>def stop(self) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Stop the engine from executing.
f5905:c0:m3
@iface.method<EOL><INDENT>def __next__(self) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Push the engine one step.
f5905:c0:m4
@iface.method<EOL><INDENT>def add(self, coro: types.CoroutineType) -> typing.Any:<DEDENT>
raise NotImplementedError()<EOL>
Add a coroutine to the engine for execution. Args: coro (types.CoroutineType): A coroutine object. Returns: typing.Any: Some opaque identifier that represents the scheduled coroutine within the engine.
f5906:c0:m0
@iface.method<EOL><INDENT>def cancel(<EOL>self,<EOL>identifier: typing.Any,<EOL>exc_type: typing.Optional[type]=None,<EOL>) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Cancel an active coroutine and remove it from the schedule. Args: identifier (typing.Any): The identifier returned from add. exc_type (typing.Optional[type]): The exception type to throw into the coroutine on cancel. No exception is thrown if nothing is given. Instead the coroutine is no longer processed. Returns: bool: True if the coroutine is cancelled. False if the identifier is invalid or if the coroutine is complete.
f5906:c0:m1
@iface.classattribute<EOL><INDENT>def default_max_listeners(self) -> int:<DEDENT>
raise NotImplementedError()<EOL>
The default number of max listeners per event before warning. A value of zero or less is the same as setting this value to float('inf').
f5908:c0:m0
@iface.attribute<EOL><INDENT>def max_listeners(self) -> int:<DEDENT>
raise NotImplementedError()<EOL>
The max listeners per event before this instance warns.
f5908:c0:m1
@iface.method<EOL><INDENT>def listeners(self, event: str) -> typing.Iterable[typing.Callable]:<DEDENT>
raise NotImplementedError()<EOL>
Get an iterable of listeners for a given event. Args: event (str): The case-sensitive name of an event. Returns: typing.Iterable[typing.Callable]: An iterable of listeners.
f5908:c0:m2
@iface.method<EOL><INDENT>def listeners_count(self, event: str) -> int:<DEDENT>
raise NotImplementedError()<EOL>
Get the number of listeners for a given event. Args: event (str): The case-sensitive name of an event. Returns: int: The number of listeners for the event.
f5908:c0:m3
@iface.method<EOL><INDENT>def on(self, event: str, listener: typing.Callable) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Add a listener for the given event. This method will not add listeners while the event is being emitted. If called while emitting the same event, the emitter will queue the request and process it after all listerners are called. Args: event (str): The case-sensitive name of an event. listener (typing.Callable): The function to execute when the event is emitted.
f5908:c0:m4
@iface.method<EOL><INDENT>def once(self, event: str, listener: typing.Callable) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Add a one time listener for the given event. Args: event (str): The case-sensitive name of an event. listener (typing.Callable): The function to execute when the event is emitted.
f5908:c0:m5
@iface.method<EOL><INDENT>def remove(self, event: str, listener: typing.Callable) -> None:<DEDENT>
raise NotImplementedError()<EOL>
Remove a listener from an event. This method removes, at most, one listener from the given event. Listeners are removed in the order in which they were registered. This method will not remove listeners while the event is being emitted. If called while emitting the same event, the emitter will queue the request and process it after all listeners are called. Args: event (str): The case-sensitive name of an event. listener (typing.Callable): A reference to the listener function to be removed.
f5908:c0:m6
@iface.method<EOL><INDENT>def emit(self, event: str, *args, **kwargs) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Call all listeners attached to the given event. All listeners are called with the args and kwargs given to this method. Returns: bool: True if the event has listeners else False.
f5908:c0:m7
def proxy_for(widget):
proxy_type = widget_proxies.get(widget.__class__)<EOL>if proxy_type is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % widget)<EOL><DEDENT>return proxy_type(widget)<EOL>
Create a proxy for a Widget :param widget: A gtk.Widget to proxy This will raise a KeyError if there is no proxy type registered for the widget type.
f5911:m0
def update(self, value):
self.update_internal(value)<EOL>self.emit('<STR_LIT>', self.get_widget_value())<EOL>
Update the widget's value
f5911:c0:m1
def read(self):
return self.get_widget_value()<EOL>
Get the widget's value
f5911:c0:m2
def update_internal(self, value):
self.block()<EOL>self.set_widget_value(value)<EOL>self.unblock()<EOL>
Update the widget's value without firing a changed signal
f5911:c0:m5
def widget_changed(self, *args):
self.emit('<STR_LIT>', self.get_widget_value())<EOL>
Called to indicate that a widget's value has been changed. This will usually be called from a proxy implementation on response to whichever signal was connected in `connect_widget` The `*args` are there so you can use this as a signal handler.
f5911:c0:m6
def set_widget_value(self, value):
Set the value of the widget. This will update the view to match the value given. This is called internally, and is called while the proxy is blocked, so no signals are emitted from this action. This method should be overriden in subclasses depending on how a widget's value is set.
f5911:c0:m7
def get_widget_value(self):
Get the widget value. This method should be overridden in subclasses to return a value from the widget.
f5911:c0:m8
def connect_widget(self):
if self.signal_name is not None:<EOL><INDENT>sid = self.widget.connect(self.signal_name, self.widget_changed)<EOL>self.connections.append(sid)<EOL><DEDENT>
Perform the initial connection of the widget the default implementation will connect to the widgets signal based on self.signal_name
f5911:c0:m9
def add_proxy(self, name, proxy):
proxy.connect('<STR_LIT>', self._on_proxy_changed, name)<EOL>
Add a proxy to this group :param name: The name or key of the proxy, which will be emitted with the changed signal :param proxy: The proxy instance to add
f5911:c16:m1
def add_proxy_for(self, name, widget):
proxy = proxy_for(widget)<EOL>self.add_proxy(name, proxy)<EOL>
Create a proxy for a widget and add it to this group :param name: The name or key of the proxy, which will be emitted with the changed signal :param widget: The widget to create a proxy for
f5911:c16:m2
def add_group(self, group):
group.connect('<STR_LIT>', self._on_group_changed)<EOL>
Add an existing group to this group and proxy its signals :param group: The ProxyGroup instance to add
f5911:c16:m3
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra):
global _old_hook<EOL>assert _old_hook is None<EOL>def new_hook(etype, eval, trace):<EOL><INDENT>gobject.idle_add(dialog_handler, dialog, etype, eval, trace, extra)<EOL>if invoke_old_hook:<EOL><INDENT>_old_hook(etype, eval, trace)<EOL><DEDENT><DEDENT>_old_hook = sys.excepthook<EOL>sys.excepthook = new_hook<EOL>
install the configured exception hook wrapping the old exception hook don't use it twice :oparam dialog: a different exception dialog class :oparam invoke_old_hook: should we invoke the old exception hook?
f5912:m2
def uninstall_hook():
global _old_hook<EOL>sys.excepthook = _old_hook<EOL>_old_hook = None<EOL>
uninstall our hook
f5912:m3
def _commonprefix(m):
if not m:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>prefix = m[<NUM_LIT:0>]<EOL>for item in m:<EOL><INDENT>for i in range(len(prefix)):<EOL><INDENT>if prefix[:i+<NUM_LIT:1>] != item[:i+<NUM_LIT:1>]:<EOL><INDENT>prefix = prefix[:i]<EOL>if i == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>break<EOL><DEDENT><DEDENT><DEDENT>return prefix<EOL>
Given a list of pathnames, returns the longest common leading component
f5913:m0
def expand_items(form_values, sep='<STR_LIT:.>'):
output = {}<EOL>for keys_str_i, value_i in form_values:<EOL><INDENT>keys_i = keys_str_i.split(sep)<EOL>parents_i = keys_i[:-<NUM_LIT:1>]<EOL>fieldname_i = keys_i[-<NUM_LIT:1>]<EOL>dict_j = output<EOL>for key_j in parents_i:<EOL><INDENT>dict_j = dict_j.setdefault(key_j, {})<EOL><DEDENT>dict_j[fieldname_i] = value_i<EOL><DEDENT>return output<EOL>
Parameters ---------- form_values : list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respective value joined by ``'.'``. For example, the key ``'a.b.c'`` would be expanded to the dictionary ``{'a': {'b': {'c': 'foo'}}}``. Returns ------- dict Nested dictionary, where levels are inferred from each key by splitting on ``'.'``.
f5915:m0
def flatten_dict(root, parents=None, sep='<STR_LIT:.>'):
if parents is None:<EOL><INDENT>parents = []<EOL><DEDENT>result = []<EOL>for i, (k, v) in enumerate(root.items()):<EOL><INDENT>parents_i = parents + [k]<EOL>key_i = sep.join(parents_i)<EOL>if isinstance(v, dict):<EOL><INDENT>value_i = flatten_dict(v, parents=parents_i, sep=sep)<EOL>result.extend(value_i)<EOL><DEDENT>else:<EOL><INDENT>value_i = v<EOL>result.append((key_i, value_i))<EOL><DEDENT><DEDENT>return result<EOL>
Args: root (dict) : Nested dictionary (e.g., JSON object). parents (list) : List of ancestor keys. Returns ------- list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respective value joined by ``'.'``. For example, for the item in the dictionary ``{'a': {'b': {'c': 'foo'}}}``, the joined key would be ``'a.b.c'``. See also :func:`expand_items`.
f5915:m2
def get_fields_frame(schema):
fields = []<EOL>def get_field_record(i, key, value, parents):<EOL><INDENT>if value.get('<STR_LIT>') or '<STR_LIT:default>' not in value:<EOL><INDENT>raise Skip<EOL><DEDENT>field = (len(parents) - <NUM_LIT:1>, i, tuple(parents[:-<NUM_LIT:1>]), parents[-<NUM_LIT:1>],<EOL>value['<STR_LIT:type>'], value['<STR_LIT:default>'])<EOL>return fields.append(field)<EOL><DEDENT>get_types(schema['<STR_LIT>'], get_field_record)<EOL>df_fields = pd.DataFrame(sorted(fields), columns=['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:default>'])<EOL>df_fields['<STR_LIT>'] = df_fields.apply(lambda row:<EOL>get_nested_item(row, schema<EOL>['<STR_LIT>'],<EOL>row.parents +<EOL>(row.field, )),<EOL>axis=<NUM_LIT:1>)<EOL>return df_fields<EOL>
Parameters ---------- schema : dict `JSON schema <http://spacetelescope.github.io/understanding-json-schema/>`_
f5915:m4
def schema_dialog(schema, data=None, device_name=None, max_width=None,<EOL>max_fps=None, **kwargs):
<EOL>if not device_name and device_name is not None:<EOL><INDENT>dialog = SchemaDialog(schema, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>with nostderr():<EOL><INDENT>import pygst_utils as pu<EOL><DEDENT>gtk.threads_init()<EOL>df_modes = pu.get_available_video_source_configs()<EOL>query = (df_modes.width == df_modes.width)<EOL>if device_name is not None:<EOL><INDENT>if isinstance(device_name, (str,)):<EOL><INDENT>query &= (df_modes.device_name == device_name)<EOL><DEDENT>else:<EOL><INDENT>query &= (df_modes.device_name.isin(device_name))<EOL><DEDENT><DEDENT>if max_width is not None:<EOL><INDENT>query &= (df_modes.width <= max_width)<EOL><DEDENT>if max_fps is not None:<EOL><INDENT>query &= (df_modes.framerate <= max_fps)<EOL><DEDENT>df_modes = df_modes.loc[query]<EOL>if not df_modes.shape[<NUM_LIT:0>]:<EOL><INDENT>raise KeyError('<STR_LIT>')<EOL><DEDENT>config = df_modes.sort_values(['<STR_LIT:width>', '<STR_LIT>'],<EOL>ascending=False).iloc[<NUM_LIT:0>]<EOL>pipeline_command = pu.pipeline_command_from_json(config,<EOL>colorspace='<STR_LIT>')<EOL>dialog = MetaDataDialog(schema, pipeline_command, **kwargs)<EOL><DEDENT>with nostderr():<EOL><INDENT>valid, results = dialog.run(values=data)<EOL><DEDENT>if not valid:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return results<EOL>
Parameters ---------- schema : dict jsonschema definition. Each property *must* have a default value. device_name : False or None or str or list_like, optional GStreamer video source device name(s). If `None` (default), first available video device is used. If `False`, video is disabled. max_width : int Maximum video frame width. max_fps : float Maximum video frame rate (frames/second). Returns ------- dict json-encodable dictionary containing validated values for properties included in the specified schema. Raises ------ KeyError If no video configuration is found that matches the specified parameters. ValueError If values to not validate.
f5915:m8
def widget_for(element):
view_type = _view_type_for_element(element)<EOL>if view_type is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % element)<EOL><DEDENT>builder = view_widgets.get(view_type)<EOL>if builder is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % view_type)<EOL><DEDENT>return builder(element)<EOL>
Create a widget for a schema item
f5916:m1
def get_first_builder_window(builder):
for obj in builder.get_objects():<EOL><INDENT>if isinstance(obj, gtk.Window):<EOL><INDENT>return obj<EOL><DEDENT><DEDENT>
Get the first toplevel widget in a gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit naming is always going to be a better situation.
f5917:m0
def get_builder_toplevel(self, builder):
raise NotImplementedError<EOL>
Get the toplevel widget from a gtk.Builder file.
f5917:c0:m1
def create_ui(self):
Create any UI by hand. Override to create additional UI here. This can contain any instance initialization, so for example mutation of the gtk.Builder generated UI, or creating the UI in its entirety.
f5917:c0:m3
def model_set(self):
This method is called when the model is changed
f5917:c0:m4
def add_slave(self, slave, container_name="<STR_LIT>"):
cont = getattr(self, container_name, None)<EOL>if cont is None:<EOL><INDENT>raise AttributeError(<EOL>'<STR_LIT>')<EOL><DEDENT>cont.add(slave.widget)<EOL>self.slaves.append(slave)<EOL>return slave<EOL>
Add a slave delegate
f5917:c0:m5
def show(self):
self.widget.show_all()<EOL>
Call show_all on the toplevel widget
f5917:c0:m6