signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _make_like(self, column, format, value):
c = []<EOL>if format.startswith('<STR_LIT:%>'):<EOL><INDENT>c.append('<STR_LIT:%>')<EOL><DEDENT>c.append(value)<EOL>if format.endswith('<STR_LIT:%>'):<EOL><INDENT>c.append('<STR_LIT:%>')<EOL><DEDENT>return column.like('<STR_LIT>'.join(c))<EOL>
make like condition :param column: column object :param format: '%_' '_%' '%_%' :param value: column value :return: condition object
f5821:c18:m6
def _make_op(self, column, op, value):
if not op:<EOL><INDENT>return None<EOL><DEDENT>if op == '<STR_LIT:>>':<EOL><INDENT>return column>value<EOL><DEDENT>elif op == '<STR_LIT:<>':<EOL><INDENT>return column<value<EOL><DEDENT>elif op == '<STR_LIT>':<EOL><INDENT>return column>=value<EOL><DEDENT>elif op == '<STR_LIT>':<EOL><INDENT>return column<=value<EOL><DEDE...
make op condition :param column: column object :param op: >, <, >=, !=, <=, ==, in_, :param value: volumn value :return: condition object
f5821:c18:m7
def fix_filename(filename, suffix='<STR_LIT>'):
if suffix:<EOL><INDENT>f, ext = os.path.splitext(filename)<EOL>return f+suffix+ext<EOL><DEDENT>else:<EOL><INDENT>return filename<EOL><DEDENT>
e.g. fix_filename('icon.png', '_40x40') return icon_40x40.png
f5823:m0
def thumbnail_image(realfile, filename, size=(<NUM_LIT:200>, <NUM_LIT>), suffix=True, quality=None):
from PIL import Image<EOL>im = Image.open(realfile)<EOL>file, ext = os.path.splitext(realfile)<EOL>if im.size[<NUM_LIT:0>]<=size[<NUM_LIT:0>] and im.size[<NUM_LIT:1>]<=size[<NUM_LIT:1>]:<EOL><INDENT>return filename, filename<EOL><DEDENT>im.thumbnail(size, Image.ANTIALIAS)<EOL>format = ext[<NUM_LIT:1>:].upper()<EOL>if f...
:param: real input filename (string) :filename: relative input filename (string) :param: suffix if True, then add '.thumbnail' to the end of filename return value should be a tuple, (saved_real_filename, saved_filename)
f5823:m2
def xhtml_escape(value):
return _XHTML_ESCAPE_RE.sub(lambda match: _XHTML_ESCAPE_DICT[match.group(<NUM_LIT:0>)],<EOL>to_basestring(value))<EOL>
Escapes a string so it is valid within HTML or XML. Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``. When used in attribute values the escaped strings must be enclosed in quotes. .. versionchanged:: 3.2 Added the single quote to the list of escaped characters.
f5824:m0
def xhtml_unescape(value):
return re.sub(r"<STR_LIT>", _convert_entity, _unicode(value))<EOL>
Un-escapes an XML-escaped string.
f5824:m1
def json_encode(value):
<EOL>return json.dumps(value).replace("<STR_LIT>", "<STR_LIT>")<EOL>
JSON-encodes the given Python object.
f5824:m2
def json_decode(value):
return json.loads(to_basestring(value))<EOL>
Returns Python objects for the given JSON string.
f5824:m3
def squeeze(value):
return re.sub(r"<STR_LIT>", "<STR_LIT:U+0020>", value).strip()<EOL>
Replace all sequences of whitespace chars with a single space.
f5824:m4
def url_escape(value, plus=True):
quote = urllib_parse.quote_plus if plus else urllib_parse.quote<EOL>return quote(utf8(value))<EOL>
Returns a URL-encoded version of the given value. If ``plus`` is true (the default), spaces will be represented as "+" instead of "%20". This is appropriate for query strings but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded...
f5824:m5
def utf8(value):
if isinstance(value, _UTF8_TYPES):<EOL><INDENT>return value<EOL><DEDENT>if not isinstance(value, unicode_type):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % type(value)<EOL>)<EOL><DEDENT>return value.encode("<STR_LIT:utf-8>")<EOL>
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
f5824:m6
def to_unicode(value):
if isinstance(value, _TO_UNICODE_TYPES):<EOL><INDENT>return value<EOL><DEDENT>if not isinstance(value, bytes_type):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % type(value)<EOL>)<EOL><DEDENT>return value.decode("<STR_LIT:utf-8>")<EOL>
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
f5824:m7
def to_basestring(value):
if isinstance(value, _BASESTRING_TYPES):<EOL><INDENT>return value<EOL><DEDENT>if not isinstance(value, bytes_type):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % type(value)<EOL>)<EOL><DEDENT>return value.decode("<STR_LIT:utf-8>")<EOL>
Converts a string argument to a subclass of basestring. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two type...
f5824:m8
def recursive_unicode(obj):
if isinstance(obj, dict):<EOL><INDENT>return dict((recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items())<EOL><DEDENT>elif isinstance(obj, list):<EOL><INDENT>return list(recursive_unicode(i) for i in obj)<EOL><DEDENT>elif isinstance(obj, tuple):<EOL><INDENT>return tuple(recursive_unicode(i) for i in obj...
Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries.
f5824:m9
def linkify(text, shorten=False, extra_params="<STR_LIT>",<EOL>require_protocol=False, permitted_protocols=["<STR_LIT:http>", "<STR_LIT>"]):
if extra_params and not callable(extra_params):<EOL><INDENT>extra_params = "<STR_LIT:U+0020>" + extra_params.strip()<EOL><DEDENT>def make_link(m):<EOL><INDENT>url = m.group(<NUM_LIT:1>)<EOL>proto = m.group(<NUM_LIT:2>)<EOL>if require_protocol and not proto:<EOL><INDENT>return url <EOL><DEDENT>if proto and proto not in...
Converts plain text into HTML with links. For example: ``linkify("Hello http://tornadoweb.org!")`` would return ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!`` Parameters: * ``shorten``: Long urls will be shortened for display. * ``extra_params``: Extra text to include in th...
f5824:m10
def signal_handler_usr1(self, signum, frame):
self.is_exit = '<STR_LIT>'<EOL>self.log.info ("<STR_LIT>" % (self.name, self.pid, signum))<EOL>os._exit(<NUM_LIT:0>)<EOL>
hard memory limit
f5825:c2:m10
def signal_handler_usr2(self, signum, frame):
self.is_exit = '<STR_LIT>'<EOL>self.log.info ("<STR_LIT>" % (self.name, self.pid, signum))<EOL>os._exit(<NUM_LIT:0>)<EOL>
soft memory limit
f5825:c2:m11
def __init__(self, workers, log=None, check_point=<NUM_LIT:10>,<EOL>title='<STR_LIT>', wait_time=<NUM_LIT:3>, daemon=False):
if not workers:<EOL><INDENT>log.info('<STR_LIT>')<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>self.log = log or logging.getLogger(__name__)<EOL>self.workers = workers<EOL>for w in self.workers:<EOL><INDENT>w.log = self.log<EOL><DEDENT>self.is_exit = False<EOL>self.check_point = check_point<EOL>self.title = title<EOL>self.wai...
:param workers: a list of workers :param log: log object :param check_point: time interval to check sub process status :return:
f5825:c3:m0
@classmethod<EOL><INDENT>def _create_class_proxy(cls, theclass):<DEDENT>
def make_method(name):<EOL><INDENT>def method(self, *args, **kw):<EOL><INDENT>return getattr(self.__get_instance__(), name)(*args, **kw)<EOL><DEDENT>return method<EOL><DEDENT>namespace = {}<EOL>for name in cls._special_names:<EOL><INDENT>if hasattr(theclass, name):<EOL><INDENT>namespace[name] = make_method(name)<EOL><D...
creates a proxy for the given class
f5826:c1:m8
def __new__(cls, env, name, klass, *args, **kwargs):
try:<EOL><INDENT>cache = cls.__dict__["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>cls._class_proxy_cache = cache = {}<EOL><DEDENT>try:<EOL><INDENT>theclass = cache[klass]<EOL><DEDENT>except KeyError:<EOL><INDENT>cache[klass] = theclass = cls._create_class_proxy(klass)<EOL><DEDENT>ins = object.__new__(theclass...
creates an proxy instance referencing `obj`. (obj, *args, **kwargs) are passed to this class' __init__, so deriving classes can define an __init__ method of their own. note: _class_proxy_cache is unique per deriving class (each deriving class must hold its own cache)
f5826:c1:m9
def encode_filename(filename, from_encoding='<STR_LIT:utf-8>', to_encoding=None):
import sys<EOL>to_encoding = to_encoding or sys.getfilesystemencoding()<EOL>from_encoding = from_encoding or sys.getfilesystemencoding()<EOL>if not isinstance(filename, str):<EOL><INDENT>try:<EOL><INDENT>f = str(filename, from_encoding)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>try:<EOL><INDENT>f = str(filenam...
>>> print encode_filename('\xe4\xb8\xad\xe5\x9b\xbd.doc') \xd6\xd0\xb9\xfa.doc >>> f = unicode('\xe4\xb8\xad\xe5\x9b\xbd.doc', 'utf-8') >>> print encode_filename(f) \xd6\xd0\xb9\xfa.doc >>> print encode_filename(f.encode('gbk'), 'gbk') \xd6\xd0\xb9\xfa.doc >>> print encode_filename(f, 'gbk', 'utf-8') \xe4\xb8\xad\xe5\x...
f5827:m2
def str_filesize(size):
import bisect<EOL>d = [(<NUM_LIT>-<NUM_LIT:1>,'<STR_LIT>'), (<NUM_LIT>**<NUM_LIT:2>-<NUM_LIT:1>,'<STR_LIT:M>'), (<NUM_LIT>**<NUM_LIT:3>-<NUM_LIT:1>,'<STR_LIT>'), (<NUM_LIT>**<NUM_LIT:4>-<NUM_LIT:1>,'<STR_LIT:T>')]<EOL>s = [x[<NUM_LIT:0>] for x in d]<EOL>index = bisect.bisect_left(s, size) - <NUM_LIT:1><EOL>if index == ...
>>> print str_filesize(0) 0 >>> print str_filesize(1023) 1023 >>> print str_filesize(1024) 1K >>> print str_filesize(1024*2) 2K >>> print str_filesize(1024**2-1) 1023K >>> print str_filesize(1024**2) 1M
f5827:m3
@contextmanager<EOL>def timeit(output):
b = time.time()<EOL>yield<EOL>print(output, '<STR_LIT>' % (time.time()-b))<EOL>
If output is string, then print the string and also time used
f5828:m0
def __init__(self, format=None, datefmt=None,<EOL>log_colors=None, reset=True, style='<STR_LIT:%>'):
if sys.version_info > (<NUM_LIT:3>, <NUM_LIT:2>):<EOL><INDENT>super(ColoredFormatter, self).__init__(<EOL>format, datefmt, style=style)<EOL><DEDENT>elif sys.version_info > (<NUM_LIT:2>, <NUM_LIT:7>):<EOL><INDENT>super(ColoredFormatter, self).__init__(format, datefmt)<EOL><DEDENT>else:<EOL><INDENT>logging.Formatter.__in...
:Parameters: - format (str): The format string to use - datefmt (str): A format string for the date - log_colors (dict): A mapping of log level names to color names - reset (bool): Implictly append a color reset to all records unless False - style ('%' or '{' or '$'): The format style to use. No meaning pri...
f5829:c1:m0
def to_timezone(dt, tzinfo=None):
if not dt:<EOL><INDENT>return dt<EOL><DEDENT>tz = pick_timezone(tzinfo, __timezone__)<EOL>if not tz:<EOL><INDENT>return dt<EOL><DEDENT>dttz = getattr(dt, '<STR_LIT>', None)<EOL>if not dttz:<EOL><INDENT>return dt.replace(tzinfo=tz)<EOL><DEDENT>else:<EOL><INDENT>return dt.astimezone(tz)<EOL><DEDENT>
Convert a datetime to timezone
f5830:m11
def to_date(dt, tzinfo=None, format=None):
d = to_datetime(dt, tzinfo, format)<EOL>if not d:<EOL><INDENT>return d<EOL><DEDENT>return date(d.year, d.month, d.day)<EOL>
Convert a datetime to date with tzinfo
f5830:m12
def to_time(dt, tzinfo=None, format=None):
d = to_datetime(dt, tzinfo, format)<EOL>if not d:<EOL><INDENT>return d<EOL><DEDENT>return time_(d.hour, d.minute, d.second, d.microsecond, tzinfo=d.tzinfo)<EOL>
Convert a datetime to time with tzinfo
f5830:m13
def to_datetime(dt, tzinfo=None, format=None):
if not dt:<EOL><INDENT>return dt<EOL><DEDENT>tz = pick_timezone(tzinfo, __timezone__)<EOL>if isinstance(dt, (str, unicode)):<EOL><INDENT>if not format:<EOL><INDENT>formats = DEFAULT_DATETIME_INPUT_FORMATS<EOL><DEDENT>else:<EOL><INDENT>formats = list(format)<EOL><DEDENT>d = None<EOL>for fmt in formats:<EOL><INDENT>try:<...
Convert a date or time to datetime with tzinfo
f5830:m14
def parse_time(t):
if isinstance(t, (str, unicode)):<EOL><INDENT>b = re_time.match(t)<EOL>if b:<EOL><INDENT>v, unit = int(b.group(<NUM_LIT:1>)), b.group(<NUM_LIT:2>)<EOL>if unit == '<STR_LIT:s>':<EOL><INDENT>return v*<NUM_LIT:1000><EOL><DEDENT>elif unit == '<STR_LIT:m>':<EOL><INDENT>return v*<NUM_LIT>*<NUM_LIT:1000><EOL><DEDENT>elif unit...
Parse string time format to microsecond
f5830:m17
def import_(module, objects=None, py2=None):
if not PY2:<EOL><INDENT>mod = __import__(module, fromlist=['<STR_LIT:*>'])<EOL>if objects:<EOL><INDENT>if not isinstance(objects, (list, tuple)):<EOL><INDENT>objects = [objects]<EOL><DEDENT>r = []<EOL>for x in objects:<EOL><INDENT>r.append(getattr(mod, x))<EOL><DEDENT>if len(r) > <NUM_LIT:1>:<EOL><INDENT>return tuple(r...
:param module: py3 compatiable module path :param objects: objects want to imported, it should be a list :param via: for some py2 module, you should give the import path according the objects which you want to imported :return: object or module Usage: import_('urllib.parse', 'urlparse') import_('urllib.par...
f5832:m1
def import_mod_attr(path):
import inspect<EOL>if isinstance(path, str):<EOL><INDENT>v = path.split('<STR_LIT::>')<EOL>if len(v) == <NUM_LIT:1>:<EOL><INDENT>module, func = path.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>module, func = v<EOL><DEDENT>mod = __import__(module, fromlist=['<STR_LIT:*>'])<EOL>f = mod<EOL>for x in f...
Import string format module, e.g. 'uliweb.orm' or an object return module object and object
f5834:m1
def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True):
default_exclude = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>default_exclude_ext = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>exclude = exclude or []<EOL>exclude_ext = exclude_ext or []<EOL><INDENT>log = logging.getLogger('<STR_LIT>')<EOL><DEDENT>if not os.path.exists(dst):<EOL><INDENT>os.makedirs(dst)<E...
mod name path mod path dst output directory resursion True will extract all sub module of mod
f5834:m6
def walk_dirs(path, include=None, include_ext=None, exclude=None,<EOL>exclude_ext=None, recursion=True, file_only=False,<EOL>use_default_pattern=True, patterns=None):
default_exclude = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>default_exclude_ext = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>exclude = exclude or []<EOL>exclude_ext = exclude_ext or []<EOL>include_ext = include_ext or []<EOL>include = include or []<EOL>if not os.path.exists(path):<EOL><INDENT>raise Stop...
path directory path resursion True will extract all sub module of mod
f5834:m8
def dumps(a, encoding='<STR_LIT:utf-8>', beautiful=False, indent=<NUM_LIT:0>, convertors=None, bool_int=False):
convertors = convertors or {}<EOL>escapechars = [("<STR_LIT:\\>", "<STR_LIT>"), ("<STR_LIT:'>", r"<STR_LIT>"), ('<STR_LIT>', r'<STR_LIT>'), ('<STR_LIT>', r'<STR_LIT>'),<EOL>('<STR_LIT:\t>', r"<STR_LIT:\t>"), ('<STR_LIT:\r>', r"<STR_LIT:\r>"), ('<STR_LIT:\n>', r"<STR_LIT:\n>")]<EOL>s = []<EOL>indent_char = '<STR_LIT:U+0...
Dumps an data type to a string :param a: variable :param encoding: :param beautiful: If using indent :param indent: :param convertors: :return:
f5834:m21
def expand_path(path):
from uliweb import application<EOL>def replace(m):<EOL><INDENT>txt = m.groups()[<NUM_LIT:0>]<EOL>if txt == '<STR_LIT>':<EOL><INDENT>return application.apps_dir<EOL><DEDENT>else:<EOL><INDENT>return pkg.resource_filename(txt, '<STR_LIT>')<EOL><DEDENT><DEDENT>p = re.sub(r_expand_path, replace, path)<EOL>return os.path.exp...
Auto search some variables defined in path string, such as: $[PROJECT]/files $[app_name]/files for $[PROJECT] will be replaced with uliweb application apps_dir directory and others will be treated as a normal python package, so uliweb will use pkg_resources to get the path of the package update: 0.2.5 changed ...
f5834:m23
def date_in(d, dates):
if not d:<EOL><INDENT>return False<EOL><DEDENT>return dates[<NUM_LIT:0>] <= d <= dates[<NUM_LIT:1>]<EOL>
compare if d in dates. dates should be a tuple or a list, for example: date_in(d, [d1, d2]) and this function will execute: d1 <= d <= d2 and if d is None, then return False
f5834:m24
def camel_to_(s):
s1 = re.sub('<STR_LIT>', r'<STR_LIT>', s)<EOL>return re.sub('<STR_LIT>', r'<STR_LIT>', s1).lower()<EOL>
Convert CamelCase to camel_case
f5834:m26
def application_path(path):
from uliweb import application<EOL>return os.path.join(application.project_dir, path)<EOL>
Join application project_dir and path
f5834:m27
def get_uuid(type=<NUM_LIT:4>):
import uuid<EOL>name = '<STR_LIT>'+str(type)<EOL>u = getattr(uuid, name)<EOL>return u().hex<EOL>
Get uuid value
f5834:m28
def pretty_dict(d, leading='<STR_LIT:U+0020>', newline='<STR_LIT:\n>', indent=<NUM_LIT:0>, tabstop=<NUM_LIT:4>, process=None):
for k, v in list(d.items()):<EOL><INDENT>if process:<EOL><INDENT>k, v = process(k, v)<EOL><DEDENT>if isinstance(v, dict):<EOL><INDENT>yield '<STR_LIT>' % (indent*tabstop*leading, simple_value(k), newline)<EOL>for x in pretty_dict(v, leading=leading, newline=newline, indent=indent+<NUM_LIT:1>, tabstop=tabstop):<EOL><IND...
Output pretty formatted dict, for example: d = {"a":"b", "c":{ "d":"e", "f":"g", } } will output: a : 'b' c : d : 'e' f : 'g'
f5834:m29
def request_url(req=None):
from uliweb import request<EOL>r = req or request<EOL>if request:<EOL><INDENT>if r.query_string:<EOL><INDENT>return r.path + '<STR_LIT:?>' + r.query_string<EOL><DEDENT>else:<EOL><INDENT>return r.path<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Get full url of a request
f5834:m30
def flat_list(*alist):
a = []<EOL>for x in alist:<EOL><INDENT>if x is None:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(x, (tuple, list)):<EOL><INDENT>a.extend([i for i in x if i is not None])<EOL><DEDENT>else:<EOL><INDENT>a.append(x)<EOL><DEDENT><DEDENT>return a<EOL>
Flat a tuple, list, single value or list of list to flat list e.g. >>> flat_list(1,2,3) [1, 2, 3] >>> flat_list(1) [1] >>> flat_list([1,2,3]) [1, 2, 3] >>> flat_list([None]) []
f5834:m33
def compare_dict(da, db):
sa = set(da.items())<EOL>sb = set(db.items())<EOL>diff = sa & sb<EOL>return dict(sa - diff), dict(sb - diff)<EOL>
Compare differencs from two dicts
f5834:m34
def get_caller(skip=None):
import inspect<EOL>from fnmatch import fnmatch<EOL>try:<EOL><INDENT>stack = inspect.stack()<EOL><DEDENT>except:<EOL><INDENT>stack = [None, inspect.currentframe()]<EOL><DEDENT>if len(stack) > <NUM_LIT:1>:<EOL><INDENT>stack.pop(<NUM_LIT:0>)<EOL>if skip and not isinstance(skip, (list, tuple)):<EOL><INDENT>skip = [skip]<EO...
Get the caller information, it'll return: module, filename, line_no
f5834:m35
def trim_path(path, length=<NUM_LIT:30>):
s = path.replace('<STR_LIT:\\>', '<STR_LIT:/>').split('<STR_LIT:/>')<EOL>t = -<NUM_LIT:1><EOL>for i in range(len(s)-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>t = len(s[i]) + t + <NUM_LIT:1><EOL>if t > length-<NUM_LIT:4>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return '<STR_LIT>' + '<STR_LIT:/>'.join(s[i+<NUM_...
trim path to specified length, for example: >>> a = '/project/apps/default/settings.ini' >>> trim_path(a) '.../apps/default/settings.ini' The real length will be length-4, it'll left '.../' for output.
f5834:m36
def get_configrable_object(key, section, cls=None):
from uliweb import UliwebError, settings<EOL>import inspect<EOL>if inspect.isclass(key) and cls and issubclass(key, cls):<EOL><INDENT>return key<EOL><DEDENT>elif isinstance(key, str):<EOL><INDENT>path = settings[section].get(key)<EOL>if path:<EOL><INDENT>_cls = import_attr(path)<EOL>return _cls<EOL><DEDENT>else:<EOL><I...
if obj is a class, then check if the class is subclass of cls or it should be object path, and it'll be imported by import_attr
f5834:m40
def format_size(size):
units = ['<STR_LIT:B>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>unit = '<STR_LIT>'<EOL>n = size<EOL>old_n = n<EOL>value = size<EOL>for i in units:<EOL><INDENT>old_n = n<EOL>x, y = divmod(n, <NUM_LIT>)<EOL>if x == <NUM_LIT:0>:<EOL><INDENT>unit = i<EOL>value = y<EOL>break<EOL><DEDENT>n = x<EOL>unit = i<EOL>value = old...
Convert size to XB, XKB, XMB, XGB :param size: length value :return: string value with size unit
f5834:m41
def convert_bytes(n):
symbols = ('<STR_LIT>', '<STR_LIT:M>', '<STR_LIT>', '<STR_LIT:T>', '<STR_LIT:P>', '<STR_LIT:E>', '<STR_LIT>', '<STR_LIT:Y>')<EOL>prefix = {}<EOL>for i, s in enumerate(symbols):<EOL><INDENT>prefix[s] = <NUM_LIT:1> << (i + <NUM_LIT:1>) * <NUM_LIT:10><EOL><DEDENT>for s in reversed(symbols):<EOL><INDENT>if n >= prefix[s]:<...
Convert a size number to 'K', 'M', .etc
f5834:m42
def pid_exists(pid):
if pid < <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>os.kill(pid, <NUM_LIT:0>)<EOL><DEDENT>except OSError as e:<EOL><INDENT>return e.errno == errno.EPERM<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>
Check whether pid exists in the current process table.
f5835:m0
def wait_pid(pid, timeout=None, callback=None):
def check_timeout(delay):<EOL><INDENT>if timeout is not None:<EOL><INDENT>if time.time() >= stop_at:<EOL><INDENT>if callback:<EOL><INDENT>callback(pid)<EOL><DEDENT>else:<EOL><INDENT>raise TimeoutExpired<EOL><DEDENT><DEDENT><DEDENT>time.sleep(delay)<EOL>return min(delay * <NUM_LIT:2>, <NUM_LIT>)<EOL><DEDENT>if timeout i...
Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expi...
f5835:m1
def filedown(environ, filename, cache=True, cache_timeout=None,<EOL>action=None, real_filename=None, x_sendfile=False,<EOL>x_header_name=None, x_filename=None, fileobj=None,<EOL>default_mimetype='<STR_LIT>'):
from .common import safe_str<EOL>from werkzeug.http import parse_range_header<EOL>guessed_type = mimetypes.guess_type(filename)<EOL>mime_type = guessed_type[<NUM_LIT:0>] or default_mimetype<EOL>real_filename = real_filename or filename<EOL>headers = []<EOL>headers.append(('<STR_LIT:Content-Type>', mime_type))<EOL>d_fil...
@param filename: is used for display in download @param real_filename: if used for the real file location @param x_urlfile: is only used in x-sendfile, and be set to x-sendfile header @param fileobj: if provided, then returned as file content @type fileobj: (fobj, mtime, size) filedown now support web server controlle...
f5836:m3
def timesince(d, now=None, pos=True, flag=False):
if not d:<EOL><INDENT>if flag:<EOL><INDENT>return <NUM_LIT:0>, '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>chunks = (<EOL>(<NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>, lambda n: ungettext('<STR_LIT>', '<STR_LIT>', n)),<EOL>(<NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:30>, lambda ...
pos means calculate which direction, pos = True, now - d, pos = False, d - now flag means return value type, True will return since, message and Flase return message >>> d = datetime.datetime(2009, 10, 1, 12, 23, 19) >>> timesince(d, d, True) >>> now = datetime.datetime(2009, 10, 1, 12, 24, 19) >>> timesince(d, now, Tr...
f5837:m0
def symlink(source, link_name):
global __CSL<EOL>if __CSL is None:<EOL><INDENT>import ctypes<EOL>csl = ctypes.windll.kernel32.CreateSymbolicLinkW<EOL>csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)<EOL>csl.restype = ctypes.c_ubyte<EOL>__CSL = csl<EOL><DEDENT>flags = <NUM_LIT:0><EOL>if source is not None and os.path.isdir(source):...
symlink(source, link_name) Creates a symbolic link pointing to source named link_name copys from http://stackoverflow.com/questions/1447575/symlinks-on-windows/7924557
f5838:m5
def _style_range(self, cell, cell_range, border=None, fill=None, font=None, alignment=None):
from openpyxl.styles import Border, Side<EOL>top = left = right = bottom = Side(border_style='<STR_LIT>', color=self.border_color)<EOL>def border_add(border, top=None, right=None, left=None, bottom=None):<EOL><INDENT>top = top or border.top<EOL>left = left or border.left<EOL>right = right or border.right<EOL>bottom = b...
Apply styles to a range of cells as if they were a single cell. :param ws: Excel worksheet instance :param range: An excel range to style (e.g. A1:F20) :param border: An openpyxl Border :param fill: An openpyxl PatternFill or GradientFill :param font: An openpyxl Font object
f5841:c1:m7
def get_template(self):
rows = []<EOL>stack = []<EOL>stack.append(rows)<EOL>top = rows<EOL>for i in range(<NUM_LIT:1>, self.sheet.max_row+<NUM_LIT:1>):<EOL><INDENT>cell = self.sheet.cell(row=i, column=<NUM_LIT:1>)<EOL>if (isinstance(cell.value, str) and<EOL>cell.value.startswith('<STR_LIT>') and<EOL>cell.value.endswith('<STR_LIT>')):<EOL><IND...
读取一个Excel模板,将此Excel的所有行读出来,并且识别特殊的标记进行记录 :return: 返回读取后的模板,结果类似: [ {'cols': #各列,与subs不会同时生效 'subs':[ #子模板 {'cols':#各列, 'subs': #子模板 'field': #对应数据中字段名称 }, ... ] 'field': #对应数据中字段名称 }, ... ] 子模板的判断根据第一列是否为 {{for field}} 来判断,结束...
f5841:c2:m3
def parse_cell(self, cell):
field = '<STR_LIT>'<EOL>if (isinstance(cell.value, str) and<EOL>cell.value.startswith('<STR_LIT>') and<EOL>cell.value.endswith('<STR_LIT>')):<EOL><INDENT>field = cell.value[<NUM_LIT:2>:-<NUM_LIT:2>].strip()<EOL>value = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>value = cell.value<EOL><DEDENT>return value, field<EOL>
Process cell field, the field format just like {{field}} :param cell: :return: value, field
f5841:c2:m4
def write_line(self, sheet, row, data):
for i, d in enumerate(row['<STR_LIT>']):<EOL><INDENT>c = sheet.cell(row=self.row, column=i+<NUM_LIT:1>)<EOL>self.write_cell(sheet, c, d, data)<EOL><DEDENT>self.row += <NUM_LIT:1><EOL>
:param sheet: :param row: template row :param data: :return:
f5841:c2:m7
def write_single(self, sheet, data):
<EOL>def _subs(sheet, subs, data):<EOL><INDENT>for d in data:<EOL><INDENT>if d:<EOL><INDENT>for line in subs:<EOL><INDENT>self.write_line(sheet, line, d)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for line in self.template:<EOL><INDENT>if line['<STR_LIT>']:<EOL><INDENT>loop_name = line['<STR_LIT>']<EOL>d = data.get(loop_name,...
:param sheet: :param data: 报文对象, dict :param template: :return:
f5841:c2:m9
def process_cell(self, row, column, cell):
value, field = self.parse_cell(cell)<EOL>if value or field:<EOL><INDENT>return {'<STR_LIT>':column, '<STR_LIT>':field, '<STR_LIT:value>':value}<EOL><DEDENT>else:<EOL><INDENT>return {}<EOL><DEDENT>
对于读模板,只记录格式为 {{xxx}} 的字段 :param cell: :return: 如果不是第一行,则每列返回{'col':列值, 'field'},否则只返回 {'value':...}
f5841:c4:m0
def match(self, row, template_row=None):
if not template_row:<EOL><INDENT>template_cols = self.template[<NUM_LIT:0>]['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>template_cols = template_row['<STR_LIT>']<EOL><DEDENT>if len(template_cols)>len(row):<EOL><INDENT>return False<EOL><DEDENT>for c in template_cols:<EOL><INDENT>text = c['<STR_LIT:value>']<EOL>if not tex...
匹配一个模板时,只比较起始行,未来考虑支持比较关键字段即可,现在是起始行的所有字段全匹配 :param row: :return:
f5841:c4:m1
def get_data(self, sheet, find=False, begin=<NUM_LIT:1>):
line = begin<EOL>for row in sheet.rows:<EOL><INDENT>if self.match(row):<EOL><INDENT>d = self.extract_data(sheet, line)<EOL>return d<EOL><DEDENT>else:<EOL><INDENT>if find:<EOL><INDENT>line += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return<EOL>
Extract data from sheet :param find: 查找模式.缺省为False.为True时,将进行递归查找 :param begin: 开始行号
f5841:c4:m3
def read_data(self, sheet, begin=None):
line = self.begin<EOL>rows = sheet.rows<EOL>for i in range(line-<NUM_LIT:1>):<EOL><INDENT>next(rows)<EOL><DEDENT>template_line = self.template[self.begin-<NUM_LIT:1>]<EOL>if not template_line['<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for row in rows:<EOL><INDENT>d = {}<EOL>for c in template_li...
用于简单模板匹配,只处理一行的模板, begin为None时自动从for行开始 :param sheet: 应该使用read_only模式打开 :param begin: :return:
f5841:c4:m4
def __init__(self, template_file, sheet_name, input_file,<EOL>use_merge=False, merge_keys=None, merge_left_join=True,<EOL>merge_verbose=False, find=False, begin=<NUM_LIT:1>, callback=None):
self.template_file = template_file<EOL>self.sheet_name = sheet_name<EOL>self.matched = False <EOL>if isinstance(input_file, str):<EOL><INDENT>self.input_file = [input_file]<EOL><DEDENT>elif isinstance(input_file, (tuple, list)):<EOL><INDENT>self.input_file = input_file<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<S...
:param template_file: :param sheet_name: :param input_file: 输入文件可以是一个list或tuple数组,如果是tuple数组,格式为: [('filename', '*'), ('filename', 'sheetname1', 'sheetname2'), 'filename'] 第一个为文件名,后面的为sheet页名称,'*'表示通配符,如果和sheet_name相同,则可以仅为字符串 如果input_file中不存在指定的Sheet,则自动取所有sheets :param use_merge: If use Merge...
f5841:c6:m0
def read(self, template, find=False, begin=<NUM_LIT:1>):
result = []<EOL>self.matched = False<EOL>for sheet in self.get_sheet():<EOL><INDENT>r = template.get_data(sheet, find=find, begin=begin)<EOL>if r is not None: <EOL><INDENT>self.matched = True<EOL>if self.merge:<EOL><INDENT>self.merge.add(r)<EOL>result = self.merge.result<EOL><DEDENT>else:<EOL><INDENT>result.extend(r)<E...
:param find: 是否使用find模式.True为递归查找.缺省为False :param begin: 开始行号. 缺省为 1
f5841:c6:m3
def __init__(self, template_file, input_file, sheet_name=None,<EOL>data_sheet_name=None,<EOL>begin=None):
self.template_file = template_file<EOL>self.sheet_name = sheet_name<EOL>self.input_file = input_file<EOL>self.begin = begin<EOL>self.data_sheet_name = data_sheet_name or sheet_name<EOL>self.template = self.get_template()<EOL>
只用来处理简单读取,即数据为单行的模式 :param template_file: :param input_file: 输入文件名 :param sheet_name: 当只有一个sheet时,不管名字对不对都进行处理 :param find: 是否查找模板,缺省为False :param begin: 是否从begin行开始,缺省为None,表示自动根据模板进行判断 :return:
f5841:c7:m0
def read(self):
for sheet in self.get_sheet():<EOL><INDENT>for row in self.template.read_data(sheet, begin=self.begin):<EOL><INDENT>yield row<EOL><DEDENT><DEDENT>
:param find: 是否使用find模式.True为递归查找.缺省为False :param begin: 开始行号. 缺省为 None, 表示使用模板计算的位置
f5841:c7:m3
def __init__(self, keys=None, left_join=True, verbose=False):
self.result = []<EOL>self.keys = keys or []<EOL>self.left_join = left_join<EOL>self.verbose = verbose<EOL>
:param alist: 将要合并的数组,每个元素为一个字典 :param keys: 指明字典的key,如果是多层,则为路径,值为list,如 ['key', 'key1/key2'] :return:
f5841:c8:m0
def should_wrap(self):
return self.convert or self.strip or self.autoreset<EOL>
True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()
f5844:c1:m1
def write_and_convert(self, text):
cursor = <NUM_LIT:0><EOL>for match in self.ANSI_RE.finditer(text):<EOL><INDENT>start, end = match.span()<EOL>self.write_plain_text(text, cursor, start)<EOL>self.convert_ansi(*match.groups())<EOL>cursor = end<EOL><DEDENT>self.write_plain_text(text, cursor, len(text))<EOL>
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
f5844:c1:m5
def _make_jsmin(python_only=False):
<EOL>if not python_only:<EOL><INDENT>try:<EOL><INDENT>import _rjsmin<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return _rjsmin.jsmin<EOL><DEDENT><DEDENT>try:<EOL><INDENT>xrange<EOL><DEDENT>except NameError:<EOL><INDENT>xrange = range <EOL><DEDENT>space_chars = r'<STR_LIT>'<EOL>line_c...
Generate JS minifier based on `jsmin.c by Douglas Crockford`_ .. _jsmin.c by Douglas Crockford: http://www.crockford.com/javascript/jsmin.c :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``
f5850:m0
def jsmin_for_posers(script):
def subber(match):<EOL><INDENT>"""<STR_LIT>"""<EOL>groups = match.groups()<EOL>return (<EOL>groups[<NUM_LIT:0>] or<EOL>groups[<NUM_LIT:1>] or<EOL>groups[<NUM_LIT:2>] or<EOL>groups[<NUM_LIT:3>] or<EOL>(groups[<NUM_LIT:4>] and '<STR_LIT:\n>') or<EOL>(groups[<NUM_LIT:5>] and '<STR_LIT:U+0020>') or<EOL>(groups[<NUM_LIT:6>]...
r""" Minify javascript based on `jsmin.c by Douglas Crockford`_\. Instead of parsing the stream char by char, it uses a regular expression approach which minifies the whole script with one big substitution regex. .. _jsmin.c by Douglas Crockford: http://www.crockford.com/javascript/jsmin.c ...
f5850:m1
def default_stream_factory(total_content_length, filename, content_type,<EOL>content_length=None):
if total_content_length > <NUM_LIT> * <NUM_LIT>:<EOL><INDENT>return TemporaryFile('<STR_LIT>')<EOL><DEDENT>return BytesIO()<EOL>
The stream factory that is used per default.
f5851:m0
def parse_form_data(environ, stream_factory=None, charset='<STR_LIT:utf-8>',<EOL>errors='<STR_LIT:replace>', max_form_memory_size=None,<EOL>max_content_length=None, cls=None,<EOL>silent=True):
return FormDataParser(stream_factory, charset, errors,<EOL>max_form_memory_size, max_content_length,<EOL>cls, silent).parse_from_environ(environ)<EOL>
Parse the form data in the environ and return it as tuple in the form ``(stream, form, files)``. You should only call this method if the transport method is `POST`, `PUT`, or `PATCH`. If the mimetype of the data transmitted is `multipart/form-data` the files multidict will be filled with `FileStorage`...
f5851:m1
def exhaust_stream(f):
def wrapper(self, stream, *args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return f(self, stream, *args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>exhaust = getattr(stream, '<STR_LIT>', None)<EOL>if exhaust is not None:<EOL><INDENT>exhaust()<EOL><DEDENT>else:<EOL><INDENT>while <NUM_LIT:1>:<EOL><INDENT>chunk = stream.rea...
Helper decorator for methods that exhausts the stream on return.
f5851:m2
def is_valid_multipart_boundary(boundary):
return _multipart_boundary_re.match(boundary) is not None<EOL>
Checks if the string given is a valid multipart boundary.
f5851:m3
def _line_parse(line):
if line[-<NUM_LIT:2>:] in ['<STR_LIT:\r\n>', b'<STR_LIT:\r\n>']:<EOL><INDENT>return line[:-<NUM_LIT:2>], True<EOL><DEDENT>elif line[-<NUM_LIT:1>:] in ['<STR_LIT:\r>', '<STR_LIT:\n>', b'<STR_LIT:\r>', b'<STR_LIT:\n>']:<EOL><INDENT>return line[:-<NUM_LIT:1>], True<EOL><DEDENT>return line, False<EOL>
Removes line ending characters and returns a tuple (`stripped_line`, `is_terminated`).
f5851:m4
def parse_multipart_headers(iterable):
result = []<EOL>for line in iterable:<EOL><INDENT>line = to_native(line)<EOL>line, line_terminated = _line_parse(line)<EOL>if not line_terminated:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not line:<EOL><INDENT>break<EOL><DEDENT>elif line[<NUM_LIT:0>] in '<STR_LIT>' and result:<EOL><INDENT>key, value = r...
Parses multipart headers from an iterable that yields lines (including the trailing newline symbol). The iterable has to be newline terminated. The iterable will stop at the line where the headers ended so it can be further consumed. :param iterable: iterable of strings that are newline terminated
f5851:m5
def parse_from_environ(self, environ):
content_type = environ.get('<STR_LIT>', '<STR_LIT>')<EOL>content_length = get_content_length(environ)<EOL>mimetype, options = parse_options_header(content_type)<EOL>return self.parse(get_input_stream(environ), mimetype,<EOL>content_length, options)<EOL>
Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``.
f5851:c0:m2
def parse(self, stream, mimetype, content_length, options=None):
if self.max_content_length is not None andcontent_length is not None andcontent_length > self.max_content_length:<EOL><INDENT>raise exceptions.RequestEntityTooLarge()<EOL><DEDENT>if options is None:<EOL><INDENT>options = {}<EOL><DEDENT>parse_func = self.get_parse_func(mimetype, options)<EOL>if parse_func is not None:<E...
Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length of the incoming data :param options: optional mimetype parameters (u...
f5851:c0:m3
def _fix_ie_filename(self, filename):
if filename[<NUM_LIT:1>:<NUM_LIT:3>] == '<STR_LIT>' or filename[:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>return filename.split('<STR_LIT:\\>')[-<NUM_LIT:1>]<EOL><DEDENT>return filename<EOL>
Internet Explorer 6 transmits the full file name if a file is uploaded. This function strips the full path if it thinks the filename is Windows-like absolute.
f5851:c1:m1
def _find_terminator(self, iterator):
for line in iterator:<EOL><INDENT>if not line:<EOL><INDENT>break<EOL><DEDENT>line = line.strip()<EOL>if line:<EOL><INDENT>return line<EOL><DEDENT><DEDENT>return b'<STR_LIT>'<EOL>
The terminator might have some additional newlines before it. There is at least one application that sends additional newlines before headers (the python setuptools package).
f5851:c1:m2
def parse_lines(self, file, boundary, content_length):
next_part = b'<STR_LIT>' + boundary<EOL>last_part = next_part + b'<STR_LIT>'<EOL>iterator = chain(make_line_iter(file, limit=content_length,<EOL>buffer_size=self.buffer_size),<EOL>_empty_string_iter)<EOL>terminator = self._find_terminator(iterator)<EOL>if terminator == last_part:<EOL><INDENT>return<EOL><DEDENT>elif ter...
Generate parts of ``('begin_form', (headers, name))`` ``('begin_file', (headers, name, filename))`` ``('cont', bytestring)`` ``('end', None)`` Always obeys the grammar parts = ( begin_form cont* end | begin_file cont* end )*
f5851:c1:m9
def parse_parts(self, file, boundary, content_length):
in_memory = <NUM_LIT:0><EOL>for ellt, ell in self.parse_lines(file, boundary, content_length):<EOL><INDENT>if ellt == _begin_file:<EOL><INDENT>headers, name, filename = ell<EOL>is_file = True<EOL>guard_memory = False<EOL>filename, container = self.start_file_streaming(<EOL>filename, headers, content_length)<EOL>_write ...
Generate ``('file', (name, val))`` and ``('form', (name, val))`` parts.
f5851:c1:m10
def _items(mappingorseq):
if hasattr(mappingorseq, "<STR_LIT>"):<EOL><INDENT>return mappingorseq.iteritems()<EOL><DEDENT>elif hasattr(mappingorseq, "<STR_LIT>"):<EOL><INDENT>return mappingorseq.items()<EOL><DEDENT>return mappingorseq<EOL>
Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v
f5853:m0
def get(self, key):
return None<EOL>
Looks up key in the cache and returns the value for it. If the key does not exist `None` is returned instead. :param key: the key to be looked up.
f5853:c0:m1
def delete(self, key):
pass<EOL>
Deletes `key` from the cache. If it does not exist in the cache nothing happens. :param key: the key to delete.
f5853:c0:m2
def get_many(self, *keys):
return map(self.get, keys)<EOL>
Returns a list of values for the given keys. For each key a item in the list is created. Example:: foo, bar = cache.get_many("foo", "bar") If a key can't be looked up `None` is returned for that key instead. :param keys: The function accepts multiple keys as positional ...
f5853:c0:m3
def get_dict(self, *keys):
return dict(zip(keys, self.get_many(*keys)))<EOL>
Works like :meth:`get_many` but returns a dict:: d = cache.get_dict("foo", "bar") foo = d["foo"] bar = d["bar"] :param keys: The function accepts multiple keys as positional arguments.
f5853:c0:m4
def set(self, key, value, timeout=None):
pass<EOL>
Adds a new key/value to the cache (overwrites value, if key already exists in the cache). :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key (if not specified, it uses the default timeout).
f5853:c0:m5
def add(self, key, value, timeout=None):
pass<EOL>
Works like :meth:`set` but does not overwrite the values of already existing keys. :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key or the default timeout if not specified.
f5853:c0:m6
def set_many(self, mapping, timeout=None):
for key, value in _items(mapping):<EOL><INDENT>self.set(key, value, timeout)<EOL><DEDENT>
Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout).
f5853:c0:m7
def delete_many(self, *keys):
for key in keys:<EOL><INDENT>self.delete(key)<EOL><DEDENT>
Deletes multiple keys at once. :param keys: The function accepts multiple keys as positional arguments.
f5853:c0:m8
def clear(self):
pass<EOL>
Clears the cache. Keep in mind that not all caches support completely clearing the cache.
f5853:c0:m9
def inc(self, key, delta=<NUM_LIT:1>):
self.set(key, (self.get(key) or <NUM_LIT:0>) + delta)<EOL>
Increments the value of a key by `delta`. If the key does not yet exist it is initialized with `delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to add.
f5853:c0:m10
def dec(self, key, delta=<NUM_LIT:1>):
self.set(key, (self.get(key) or <NUM_LIT:0>) - delta)<EOL>
Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract.
f5853:c0:m11
def import_preferred_memcache_lib(self, servers):
try:<EOL><INDENT>import pylibmc<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return pylibmc.Client(servers)<EOL><DEDENT>try:<EOL><INDENT>from google.appengine.api import memcache<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return memcache.Client()<EOL...
Returns an initialized memcache client. Used by the constructor.
f5853:c3:m12
def dump_object(self, value):
t = type(value)<EOL>if t is int or t is long:<EOL><INDENT>return str(value)<EOL><DEDENT>return '<STR_LIT:!>' + pickle.dumps(value)<EOL>
Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else.
f5853:c4:m1
def load_object(self, value):
if value is None:<EOL><INDENT>return None<EOL><DEDENT>if value.startswith('<STR_LIT:!>'):<EOL><INDENT>return pickle.loads(value[<NUM_LIT:1>:])<EOL><DEDENT>try:<EOL><INDENT>return int(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>return value<EOL><DEDENT>
The reversal of :meth:`dump_object`. This might be callde with None.
f5853:c4:m2
def _list_dir(self):
return [os.path.join(self._path, fn) for fn in os.listdir(self._path)<EOL>if not fn.endswith(self._fs_transaction_suffix)]<EOL>
return a list of (fully qualified) cache filenames
f5853:c5:m1
def generate_map(map, name='<STR_LIT>'):
from warnings import warn<EOL>warn(DeprecationWarning('<STR_LIT>'))<EOL>map.update()<EOL>rules = []<EOL>converters = []<EOL>for rule in map.iter_rules():<EOL><INDENT>trace = [{<EOL>'<STR_LIT>': is_dynamic,<EOL>'<STR_LIT:data>': data<EOL>} for is_dynamic, data in rule._trace]<EOL>rule_converters = {}<EOL>for k...
Generates a JavaScript function containing the rules defined in this map, to be used with a MapAdapter's generate_javascript method. If you don't pass a name the returned JavaScript code is an expression that returns a function. Otherwise it's a standalone script that assigns the function with that name. Dotted name...
f5854:m1