desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Set the meta field for a key to a new value. This triggers the on-change handler for existing keys.'
def meta_set(self, key, metafield, value):
self._meta.setdefault(key, {})[metafield] = value if (key in self): self[key] = self[key]
'Return an iterable of meta field names defined for a key.'
def meta_list(self, key):
return self._meta.get(key, {}).keys()
'Return the current default application.'
def __call__(self):
return self[(-1)]
'Add a new :class:`Bottle` instance to the stack'
def push(self, value=None):
if (not isinstance(value, Bottle)): value = Bottle() self.append(value) return value
'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__)'
def add_path(self, path, base=None, index=None, create=False):
base = os.path.abspath(os.path.dirname((base or self.base))) path = os.path.abspath(os.path.join(base, os.path.dirname(path))) path += os.sep if (path in self.path): self.path.remove(path) if (create and (not os.path.isdir(path))): os.makedirs(path) if (index is None): self.path.append(path) else: self.path.insert(index, path) self.cache.clear() return os.path.exists(path)
'Iterate over all existing files in all registered paths.'
def __iter__(self):
search = self.path[:] while search: path = search.pop() if (not os.path.isdir(path)): continue for name in os.listdir(path): full = os.path.join(path, name) if os.path.isdir(full): search.append(full) else: (yield full)
'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.'
def lookup(self, name):
if ((name not in self.cache) or DEBUG): for path in self.path: fpath = os.path.join(path, name) if os.path.isfile(fpath): if (self.cachemode in ('all', 'found')): self.cache[name] = fpath return fpath if (self.cachemode == 'all'): self.cache[name] = None return self.cache[name]
'Find a resource and return a file object, or raise IOError.'
def open(self, name, mode='r', *args, **kwargs):
fname = self.lookup(name) if (not fname): raise IOError(('Resource %r not found.' % name)) return self.opener(fname, mode=mode, *args, **kwargs)
'Wrapper for file uploads.'
def __init__(self, fileobj, name, filename, headers=None):
self.file = fileobj self.name = name self.raw_filename = filename self.headers = (HeaderDict(headers) if headers else HeaderDict())
'Name of the file on the client file system, but normalized to ensure file system compatibility. An empty filename is returned as \'empty\'. Only ASCII letters, digits, dashes, underscores and dots are allowed in the final filename. Accents are removed, if possible. Whitespace is replaced by a single dash. Leading or tailing dots or dashes are removed. The filename is limited to 255 characters.'
@cached_property def filename(self):
fname = self.raw_filename if (not isinstance(fname, unicode)): fname = fname.decode('utf8', 'ignore') fname = normalize('NFKD', fname) fname = fname.encode('ASCII', 'ignore').decode('ASCII') fname = os.path.basename(fname.replace('\\', os.path.sep)) fname = re.sub('[^a-zA-Z0-9-_.\\s]', '', fname).strip() fname = re.sub('[-\\s]+', '-', fname).strip('.-') return (fname[:255] or 'empty')
'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)'
def save(self, destination, overwrite=False, chunk_size=(2 ** 16)):
if isinstance(destination, basestring): if os.path.isdir(destination): destination = os.path.join(destination, self.filename) if ((not overwrite) and os.path.exists(destination)): raise IOError('File exists.') with open(destination, 'wb') as fp: self._copy_file(fp, chunk_size) else: self._copy_file(destination, chunk_size)
'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.'
def __init__(self, source=None, name=None, lookup=None, encoding='utf8', **settings):
self.name = name self.source = (source.read() if hasattr(source, 'read') else source) self.filename = (source.filename if hasattr(source, 'filename') else None) self.lookup = ([os.path.abspath(x) for x in lookup] if lookup else []) self.encoding = encoding self.settings = self.settings.copy() self.settings.update(settings) if ((not self.source) and self.name): self.filename = self.search(self.name, self.lookup) if (not self.filename): raise TemplateError(('Template %s not found.' % repr(name))) if ((not self.source) and (not self.filename)): raise TemplateError('No template specified.') self.prepare(**self.settings)
'Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.'
@classmethod def search(cls, name, lookup=None):
if (not lookup): depr('The template lookup path list should not be empty.', True) lookup = ['.'] if (os.path.isabs(name) and os.path.isfile(name)): depr('Absolute template path names are deprecated.', True) return os.path.abspath(name) for spath in lookup: spath = (os.path.abspath(spath) + os.sep) fname = os.path.abspath(os.path.join(spath, name)) if (not fname.startswith(spath)): continue if os.path.isfile(fname): return fname for ext in cls.extensions: if os.path.isfile(('%s.%s' % (fname, ext))): return ('%s.%s' % (fname, ext))
'This reads or sets the global settings stored in class.settings.'
@classmethod def global_config(cls, key, *args):
if args: cls.settings = cls.settings.copy() cls.settings[key] = args[0] else: return cls.settings[key]
'Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.'
def prepare(self, **options):
raise NotImplementedError
'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).'
def render(self, *args, **kwargs):
raise NotImplementedError
'Render the template using keyword arguments as local variables.'
def render(self, *args, **kwargs):
env = {} stdout = [] for dictarg in args: env.update(dictarg) env.update(kwargs) self.execute(stdout, env) return ''.join(stdout)
'Tokens as a space separated string (default: <% %> % {{ }})'
def get_syntax(self):
return self._syntax
'reset analyser, clear any state'
def reset(self):
self._mDone = False self._mTotalChars = 0 self._mFreqChars = 0
'feed a character with known length'
def feed(self, aBuf, aCharLen):
if (aCharLen == 2): order = self.get_order(aBuf) else: order = (-1) if (order >= 0): self._mTotalChars += 1 if (order < self._mTableSize): if (512 > self._mCharToFreqOrder[order]): self._mFreqChars += 1
'return confidence based on existing data'
def get_confidence(self):
if ((self._mTotalChars <= 0) or (self._mFreqChars <= MINIMUM_DATA_THRESHOLD)): return SURE_NO if (self._mTotalChars != self._mFreqChars): r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio)) if (r < SURE_YES): return r return SURE_YES
'Create a new libmagic wrapper. mime - if True, mimetypes are returned instead of textual descriptions mime_encoding - if True, codec is returned magic_file - use a mime database other than the system default'
def __init__(self, mime=False, magic_file=None, mime_encoding=False):
flags = MAGIC_NONE if mime: flags |= MAGIC_MIME elif mime_encoding: flags |= MAGIC_MIME_ENCODING self.cookie = magic_open(flags) magic_load(self.cookie, magic_file)
'Identify the contents of `buf`'
def from_buffer(self, buf):
return magic_buffer(self.cookie, buf)
'Identify the contents of file `filename` raises IOError if the file does not exist'
def from_file(self, filename):
if (not os.path.exists(filename)): raise IOError(('File does not exist: ' + filename)) return magic_file(self.cookie, filename)