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><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.in_(value)<EOL><DEDENT>else:<EOL><INDENT>raise KeyError('<STR_LIT>' % op)<EOL><DEDENT>
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 format == '<STR_LIT>':<EOL><INDENT>format = '<STR_LIT>'<EOL><DEDENT>if suffix:<EOL><INDENT>ofile = file + "<STR_LIT>" + ext<EOL><DEDENT>else:<EOL><INDENT>ofile = realfile<EOL><DEDENT>im.save(ofile, format, quality=quality or QUALITY)<EOL>file1, ext1 = os.path.splitext(filename)<EOL>if suffix:<EOL><INDENT>ofile1 = file1 + "<STR_LIT>" + ext<EOL><DEDENT>else:<EOL><INDENT>ofile1 = filename<EOL><DEDENT>return ofile, ofile1<EOL>
: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:: 3.1 The ``plus`` argument
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 types are not interchangeable, so this method is needed to convert byte strings to unicode.
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)<EOL><DEDENT>elif isinstance(obj, bytes_type):<EOL><INDENT>return to_unicode(obj)<EOL><DEDENT>else:<EOL><INDENT>return obj<EOL><DEDENT>
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 permitted_protocols:<EOL><INDENT>return url <EOL><DEDENT>href = m.group(<NUM_LIT:1>)<EOL>if not proto:<EOL><INDENT>href = "<STR_LIT>" + href <EOL><DEDENT>if callable(extra_params):<EOL><INDENT>params = "<STR_LIT:U+0020>" + extra_params(href).strip()<EOL><DEDENT>else:<EOL><INDENT>params = extra_params<EOL><DEDENT>max_len = <NUM_LIT:30><EOL>if shorten and len(url) > max_len:<EOL><INDENT>before_clip = url<EOL>if proto:<EOL><INDENT>proto_len = len(proto) + <NUM_LIT:1> + len(m.group(<NUM_LIT:3>) or "<STR_LIT>") <EOL><DEDENT>else:<EOL><INDENT>proto_len = <NUM_LIT:0><EOL><DEDENT>parts = url[proto_len:].split("<STR_LIT:/>")<EOL>if len(parts) > <NUM_LIT:1>:<EOL><INDENT>url = url[:proto_len] + parts[<NUM_LIT:0>] + "<STR_LIT:/>" +parts[<NUM_LIT:1>][:<NUM_LIT:8>].split('<STR_LIT:?>')[<NUM_LIT:0>].split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL><DEDENT>if len(url) > max_len * <NUM_LIT>: <EOL><INDENT>url = url[:max_len]<EOL><DEDENT>if url != before_clip:<EOL><INDENT>amp = url.rfind('<STR_LIT:&>')<EOL>if amp > max_len - <NUM_LIT:5>:<EOL><INDENT>url = url[:amp]<EOL><DEDENT>url += "<STR_LIT>"<EOL>if len(url) >= len(before_clip):<EOL><INDENT>url = before_clip<EOL><DEDENT>else:<EOL><INDENT>params += '<STR_LIT>' % href<EOL><DEDENT><DEDENT><DEDENT>return u('<STR_LIT>') % (href, params, url)<EOL><DEDENT>text = _unicode(xhtml_escape(text))<EOL>return _URL_RE.sub(make_link, text)<EOL>
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 the link tag, or a callable taking the link as an argument and returning the extra text e.g. ``linkify(text, extra_params='rel="nofollow" class="external"')``, or:: def extra_params_cb(url): if url.startswith("http://example.com"): return 'class="internal"' else: return 'class="external" rel="nofollow"' linkify(text, extra_params=extra_params_cb) * ``require_protocol``: Only linkify urls which include a protocol. If this is False, urls such as www.facebook.com will also be linkified. * ``permitted_protocols``: List (or set) of protocols which should be linkified, e.g. ``linkify(text, permitted_protocols=["http", "ftp", "mailto"])``. It is very unsafe to include protocols such as ``javascript``.
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.wait_time = wait_time<EOL>self.daemon = daemon<EOL>
: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><DEDENT><DEDENT>return type("<STR_LIT>" % (cls.__name__, theclass.__name__), (cls,), namespace)<EOL>
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)<EOL>return ins<EOL>
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(filename, '<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>raise Exception("<STR_LIT>" % filename)<EOL><DEDENT><DEDENT>filename = f<EOL><DEDENT>if to_encoding:<EOL><INDENT>return filename.encode(to_encoding)<EOL><DEDENT>else:<EOL><INDENT>return filename<EOL><DEDENT>
>>> 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\x9b\xbd.doc >>> print encode_filename('\xe4\xb8\xad\xe5\x9b\xbd.doc', 'utf-8', 'gbk') \xd6\xd0\xb9\xfa.doc
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 == -<NUM_LIT:1>:<EOL><INDENT>return str(size)<EOL><DEDENT>else:<EOL><INDENT>b, u = d[index]<EOL><DEDENT>return str(size / (b+<NUM_LIT:1>)) + u<EOL>
>>> 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.__init__(self, format, datefmt)<EOL><DEDENT>self.log_colors = default_log_colors<EOL>self.log_colors.update(log_colors or {})<EOL>self.reset = reset<EOL>
: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 prior to Python 3.2. The ``format``, ``datefmt`` and ``style`` args are passed on to the Formatter constructor.
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:<EOL><INDENT>d = datetime.strptime(dt, fmt)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if not d:<EOL><INDENT>return None<EOL><DEDENT>d = d.replace(tzinfo=tz)<EOL><DEDENT>else:<EOL><INDENT>d = datetime(getattr(dt, '<STR_LIT>', <NUM_LIT>), getattr(dt, '<STR_LIT>', <NUM_LIT:1>),<EOL>getattr(dt, '<STR_LIT>', <NUM_LIT:1>), getattr(dt, '<STR_LIT>', <NUM_LIT:0>), getattr(dt, '<STR_LIT>', <NUM_LIT:0>),<EOL>getattr(dt, '<STR_LIT>', <NUM_LIT:0>), getattr(dt, '<STR_LIT>', <NUM_LIT:0>))<EOL>if not getattr(dt, '<STR_LIT>', None):<EOL><INDENT>d = d.replace(tzinfo=tz)<EOL><DEDENT>else:<EOL><INDENT>d = d.replace(tzinfo=dt.tzinfo)<EOL><DEDENT><DEDENT>return to_timezone(d, tzinfo)<EOL>
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 == '<STR_LIT:h>':<EOL><INDENT>return v*<NUM_LIT>*<NUM_LIT>*<NUM_LIT:1000><EOL><DEDENT>else:<EOL><INDENT>return v<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TimeFormatError(t)<EOL><DEDENT><DEDENT>elif isinstance(t, (int, long)):<EOL><INDENT>return t<EOL><DEDENT>else:<EOL><INDENT>raise TimeFormatError(t)<EOL><DEDENT>
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)<EOL><DEDENT>else:<EOL><INDENT>return r[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return mod<EOL><DEDENT><DEDENT>else:<EOL><INDENT>path = modules_mapping.get(module)<EOL>if not path:<EOL><INDENT>raise Exception("<STR_LIT>".format(module))<EOL><DEDENT>if objects:<EOL><INDENT>if not isinstance(objects, (list, tuple)):<EOL><INDENT>objects = [objects]<EOL><DEDENT>r = []<EOL>for x in objects:<EOL><INDENT>m = path.get(x)<EOL>if not m:<EOL><INDENT>raise Exception("<STR_LIT>".format(x, path))<EOL><DEDENT>mod = __import__(m, fromlist=['<STR_LIT:*>'])<EOL>r.append(getattr(mod, x))<EOL><DEDENT>if len(r) > <NUM_LIT:1>:<EOL><INDENT>return tuple(r)<EOL><DEDENT>else:<EOL><INDENT>return r[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(path, (dict, list)):<EOL><INDENT>if not py2:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>path = py2<EOL><DEDENT>mod = __import__(path, fromlist=['<STR_LIT:*>'])<EOL>return mod<EOL><DEDENT><DEDENT>
: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.parse', ['urlparse', 'urljoin']) import_('urllib.parse', py2='urllib2')
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 func.split('<STR_LIT:.>'):<EOL><INDENT>try:<EOL><INDENT>f = getattr(f, x)<EOL><DEDENT>except:<EOL><INDENT>raise AttributeError("<STR_LIT>" % (x, path))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>f = path<EOL>mod = inspect.getmodule(path)<EOL><DEDENT>return mod, f<EOL>
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)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % dst)<EOL><DEDENT><DEDENT>for r in pkg.resource_listdir(mod, path):<EOL><INDENT>if r in exclude or r in default_exclude:<EOL><INDENT>continue<EOL><DEDENT>fpath = os.path.join(path, r)<EOL>if pkg.resource_isdir(mod, fpath):<EOL><INDENT>if recursion:<EOL><INDENT>extract_dirs(mod, fpath, os.path.join(dst, r), verbose, exclude, exclude_ext, recursion, replace)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ext = os.path.splitext(fpath)[<NUM_LIT:1>]<EOL>if ext in exclude_ext or ext in default_exclude_ext:<EOL><INDENT>continue<EOL><DEDENT>extract_file(mod, fpath, dst, verbose, replace)<EOL><DEDENT><DEDENT>
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 StopIteration<EOL><DEDENT>for r in os.listdir(path):<EOL><INDENT>if match(r, exclude) or (use_default_pattern and r in default_exclude):<EOL><INDENT>continue<EOL><DEDENT>if include and r not in include:<EOL><INDENT>continue<EOL><DEDENT>fpath = os.path.join(path, r)<EOL>if os.path.isdir(fpath):<EOL><INDENT>if not file_only:<EOL><INDENT>if patterns and match(r, patterns):<EOL><INDENT>yield os.path.normpath(fpath).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT><DEDENT>if recursion:<EOL><INDENT>for f in walk_dirs(fpath, include, include_ext, exclude,<EOL>exclude_ext, recursion, file_only, use_default_pattern, patterns):<EOL><INDENT>yield os.path.normpath(f).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>ext = os.path.splitext(fpath)[<NUM_LIT:1>]<EOL>if ext in exclude_ext or (use_default_pattern and ext in default_exclude_ext):<EOL><INDENT>continue<EOL><DEDENT>if include_ext and ext not in include_ext:<EOL><INDENT>continue<EOL><DEDENT>if patterns:<EOL><INDENT>if not match(r, patterns):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>yield os.path.normpath(fpath).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT><DEDENT>
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+0020>'*<NUM_LIT:4><EOL>if isinstance(a, (list, tuple)):<EOL><INDENT>if isinstance(a, list):<EOL><INDENT>s.append('<STR_LIT:[>')<EOL><DEDENT>else:<EOL><INDENT>if beautiful:<EOL><INDENT>s.append(indent_char*indent)<EOL><DEDENT>s.append('<STR_LIT:(>')<EOL><DEDENT>if beautiful:<EOL><INDENT>s.append('<STR_LIT:\n>')<EOL><DEDENT>for i, k in enumerate(a):<EOL><INDENT>if beautiful:<EOL><INDENT>ind = indent + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>ind = indent<EOL><DEDENT>s.append(indent_char*ind + dumps(k, encoding, beautiful, ind, convertors=convertors))<EOL>if i<len(a)-<NUM_LIT:1>:<EOL><INDENT>if beautiful:<EOL><INDENT>s.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>s.append('<STR_LIT:U+002CU+0020>')<EOL><DEDENT><DEDENT><DEDENT>if beautiful:<EOL><INDENT>s.append('<STR_LIT:\n>')<EOL><DEDENT>if isinstance(a, list):<EOL><INDENT>if beautiful:<EOL><INDENT>s.append(indent_char*indent)<EOL><DEDENT>s.append('<STR_LIT:]>')<EOL><DEDENT>else:<EOL><INDENT>if len(a) == <NUM_LIT:1>:<EOL><INDENT>s.append('<STR_LIT:U+002C>')<EOL><DEDENT>if beautiful:<EOL><INDENT>s.append(indent_char*indent)<EOL><DEDENT>s.append('<STR_LIT:)>')<EOL><DEDENT><DEDENT>elif isinstance(a, dict):<EOL><INDENT>s.append('<STR_LIT:{>')<EOL>if beautiful:<EOL><INDENT>s.append('<STR_LIT:\n>')<EOL><DEDENT>for i, k in enumerate(a.items()):<EOL><INDENT>key, value = k<EOL>if beautiful:<EOL><INDENT>ind = indent + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>ind = indent<EOL><DEDENT>s.append('<STR_LIT>' % (indent_char*ind + dumps(key, encoding, beautiful, ind, convertors=convertors),<EOL>dumps(value, encoding, beautiful, ind, convertors=convertors)))<EOL>if i<len(list(a.items()))-<NUM_LIT:1>:<EOL><INDENT>if beautiful:<EOL><INDENT>s.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>s.append('<STR_LIT:U+002CU+0020>')<EOL><DEDENT><DEDENT><DEDENT>if beautiful:<EOL><INDENT>s.append('<STR_LIT:\n>')<EOL>s.append(indent_char*indent)<EOL><DEDENT>s.append('<STR_LIT:}>')<EOL><DEDENT>elif isinstance(a, str):<EOL><INDENT>t = a<EOL>for i in escapechars:<EOL><INDENT>t = t.replace(i[<NUM_LIT:0>], i[<NUM_LIT:1>])<EOL><DEDENT>s.append("<STR_LIT>" % t)<EOL><DEDENT>elif isinstance(a, str):<EOL><INDENT>t = a<EOL>for i in escapechars:<EOL><INDENT>t = t.replace(i[<NUM_LIT:0>], i[<NUM_LIT:1>])<EOL><DEDENT>s.append("<STR_LIT>" % t.encode(encoding))<EOL><DEDENT>else:<EOL><INDENT>_type = type(a)<EOL>c_func = convertors.get(_type)<EOL>if c_func:<EOL><INDENT>s.append(c_func(a))<EOL><DEDENT>else:<EOL><INDENT>s.append(str(str_value(a, none='<STR_LIT:None>', bool_int=bool_int)))<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(s)<EOL>
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.expandvars(os.path.expanduser(path))<EOL>
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 from ${} to $[] Also apply with os.path.expandvars(os.path.expanduser(path))
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><INDENT>yield x<EOL><DEDENT>continue<EOL><DEDENT>yield '<STR_LIT>' % (indent*tabstop*leading, simple_value(k), simple_value(v), newline)<EOL><DEDENT>
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]<EOL><DEDENT>else:<EOL><INDENT>skip = []<EOL><DEDENT>ptn = [os.path.splitext(s.replace('<STR_LIT:\\>', '<STR_LIT:/>'))[<NUM_LIT:0>] for s in skip]<EOL>for frame in stack:<EOL><INDENT>if isinstance(frame, tuple):<EOL><INDENT>filename, funcname, lineno = frame[<NUM_LIT:1>], frame[<NUM_LIT:3>], frame[<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>filename, funcname, lineno = frame.f_code.co_filename, frame.f_code.co_name, frame.f_lineno<EOL><DEDENT>del frame<EOL>found = False<EOL>for k in ptn:<EOL><INDENT>filename = os.path.splitext(filename.replace('<STR_LIT:\\>', '<STR_LIT:/>'))[<NUM_LIT:0>]<EOL>if fnmatch(filename, k):<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>return filename, lineno, funcname<EOL><DEDENT><DEDENT><DEDENT>
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_LIT:1>:])<EOL>
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><INDENT>raise UliwebError("<STR_LIT>" % section)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise UliwebError("<STR_LIT>" % (key, cls))<EOL><DEDENT>
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_n<EOL><DEDENT>return str(value)+unit<EOL>
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]:<EOL><INDENT>value = float(n) / prefix[s]<EOL>return '<STR_LIT>' % (value, s)<EOL><DEDENT><DEDENT>return "<STR_LIT>" % n<EOL>
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 is not None:<EOL><INDENT>waitcall = lambda: os.waitpid(pid, os.WNOHANG)<EOL>stop_at = time.time() + timeout<EOL><DEDENT>else:<EOL><INDENT>waitcall = lambda: os.waitpid(pid, <NUM_LIT:0>)<EOL><DEDENT>delay = <NUM_LIT><EOL>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>retpid, status = waitcall()<EOL><DEDENT>except OSError as err:<EOL><INDENT>if err.errno == errno.EINTR:<EOL><INDENT>delay = check_timeout(delay)<EOL>continue<EOL><DEDENT>elif err.errno == errno.ECHILD:<EOL><INDENT>while <NUM_LIT:1>:<EOL><INDENT>if pid_exists(pid):<EOL><INDENT>delay = check_timeout(delay)<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if retpid == <NUM_LIT:0>:<EOL><INDENT>delay = check_timeout(delay)<EOL>continue<EOL><DEDENT>if os.WIFSIGNALED(status):<EOL><INDENT>return os.WTERMSIG(status)<EOL><DEDENT>elif os.WIFEXITED(status):<EOL><INDENT>return os.WEXITSTATUS(status)<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>
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 expired (if specified).
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_filename = _get_download_filename(environ, os.path.basename(filename))<EOL>if action == '<STR_LIT>':<EOL><INDENT>headers.append(('<STR_LIT>', '<STR_LIT>' % d_filename))<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>headers.append(('<STR_LIT>', '<STR_LIT>' % d_filename))<EOL><DEDENT>if x_sendfile:<EOL><INDENT>if not x_header_name or not x_filename:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>headers.append((x_header_name, safe_str(x_filename)))<EOL>return Response('<STR_LIT>', status=<NUM_LIT:200>, headers=headers,<EOL>direct_passthrough=True)<EOL><DEDENT>else:<EOL><INDENT>request = environ.get('<STR_LIT>')<EOL>if request:<EOL><INDENT>range = request.range<EOL><DEDENT>else:<EOL><INDENT>range = parse_range_header(environ.get('<STR_LIT>'))<EOL><DEDENT>if range and range.units=="<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>fsize = os.path.getsize(real_filename)<EOL><DEDENT>except OSError as e:<EOL><INDENT>return Response("<STR_LIT>",status=<NUM_LIT>)<EOL><DEDENT>mtime = datetime.utcfromtimestamp(os.path.getmtime(real_filename))<EOL>mtime_str = http_date(mtime)<EOL>if cache:<EOL><INDENT>etag = _generate_etag(mtime, fsize, real_filename)<EOL><DEDENT>else:<EOL><INDENT>etag = mtime_str<EOL><DEDENT>if_range = environ.get('<STR_LIT>')<EOL>if if_range:<EOL><INDENT>check_if_range_ok = (if_range.strip('<STR_LIT:">')==etag)<EOL><DEDENT>else:<EOL><INDENT>check_if_range_ok = True<EOL><DEDENT>rbegin,rend = range.ranges[<NUM_LIT:0>]<EOL>if check_if_range_ok and (rbegin+<NUM_LIT:1>)<fsize:<EOL><INDENT>if rend == None:<EOL><INDENT>rend = fsize<EOL><DEDENT>headers.append(('<STR_LIT>',str(rend-rbegin)))<EOL>headers.append(('<STR_LIT>','<STR_LIT>' %(range.units,rbegin, rend-<NUM_LIT:1>, fsize)))<EOL>headers.append(('<STR_LIT>', mtime_str))<EOL>if cache:<EOL><INDENT>headers.append(('<STR_LIT>', '<STR_LIT>' % etag))<EOL><DEDENT>if (rend-rbegin) < FileIterator.chunk_size:<EOL><INDENT>s = "<STR_LIT>".join([chunk for chunk in FileIterator(real_filename,rbegin,rend)])<EOL>return Response(s,status=<NUM_LIT>, headers=headers, direct_passthrough=True)<EOL><DEDENT>else:<EOL><INDENT>return Response(FileIterator(real_filename,rbegin,rend),<EOL>status=<NUM_LIT>, headers=headers, direct_passthrough=True)<EOL><DEDENT><DEDENT><DEDENT>if fileobj:<EOL><INDENT>f, mtime, file_size = fileobj<EOL><DEDENT>else:<EOL><INDENT>f, mtime, file_size = _opener(real_filename)<EOL><DEDENT>headers.append(('<STR_LIT>', http_date()))<EOL>if cache:<EOL><INDENT>etag = _generate_etag(mtime, file_size, real_filename)<EOL>headers += [<EOL>('<STR_LIT>', '<STR_LIT>' % etag),<EOL>]<EOL>if cache_timeout:<EOL><INDENT>headers += [<EOL>('<STR_LIT>', '<STR_LIT>' % cache_timeout),<EOL>('<STR_LIT>', http_date(time() + cache_timeout))<EOL>]<EOL><DEDENT>if not is_resource_modified(environ, etag, last_modified=mtime):<EOL><INDENT>f.close()<EOL>return Response(status=<NUM_LIT>, headers=headers)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>headers.append(('<STR_LIT>', '<STR_LIT>'))<EOL><DEDENT>headers.extend((<EOL>('<STR_LIT>', str(file_size)),<EOL>('<STR_LIT>', http_date(mtime))<EOL>))<EOL>return Response(wrap_file(environ, f), status=<NUM_LIT:200>, headers=headers,<EOL>direct_passthrough=True)<EOL><DEDENT>
@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 controlled download, you should set xsendfile=True, and add x_header, for example: nginx ('X-Accel-Redirect', '/path/to/local_url') apache ('X-Sendfile', '/path/to/local_url')
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 n: ungettext('<STR_LIT>', '<STR_LIT>', n)),<EOL>(<NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:7>, lambda n : ungettext('<STR_LIT>', '<STR_LIT>', n)),<EOL>(<NUM_LIT> * <NUM_LIT> * <NUM_LIT>, lambda n : ungettext('<STR_LIT>', '<STR_LIT>', n)),<EOL>(<NUM_LIT> * <NUM_LIT>, lambda n: ungettext('<STR_LIT>', '<STR_LIT>', n)),<EOL>(<NUM_LIT>, lambda n: ungettext('<STR_LIT>', '<STR_LIT>', n))<EOL>)<EOL>if not now:<EOL><INDENT>now = date.now()<EOL><DEDENT>else:<EOL><INDENT>now = date.to_datetime(now)<EOL><DEDENT>d = date.to_datetime(d)<EOL>delta = now - (d - datetime.timedelta(<NUM_LIT:0>, <NUM_LIT:0>, d.microsecond))<EOL>oldsince = since = delta.days * <NUM_LIT> * <NUM_LIT> * <NUM_LIT> + delta.seconds<EOL>suffix = '<STR_LIT>'<EOL>if pos:<EOL><INDENT>if since >= <NUM_LIT:0>:<EOL><INDENT>suffix = ugettext('<STR_LIT>')<EOL><DEDENT>elif since < <NUM_LIT:0>:<EOL><INDENT>suffix = ugettext('<STR_LIT>')<EOL>since *= -<NUM_LIT:1><EOL><DEDENT><DEDENT>for i, (seconds, name) in enumerate(chunks):<EOL><INDENT>count = since // seconds<EOL>if count != <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>s = ('<STR_LIT>') % {'<STR_LIT>': count, '<STR_LIT:type>': name(count)}<EOL>if i + <NUM_LIT:1> < len(chunks):<EOL><INDENT>seconds2, name2 = chunks[i + <NUM_LIT:1>]<EOL>count2 = (since - (seconds * count)) // seconds2<EOL>if count2 != <NUM_LIT:0>:<EOL><INDENT>s += ('<STR_LIT>') % {'<STR_LIT>': count2, '<STR_LIT:type>': name2(count2)}<EOL><DEDENT><DEDENT>if flag:<EOL><INDENT>return oldsince, s + suffix<EOL><DEDENT>else:<EOL><INDENT>return s + suffix<EOL><DEDENT>
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, True) u'1 minute ago' >>> now = datetime.datetime(2009, 10, 1, 12, 24, 30) >>> timesince(d, now, True) u'1 minute ago' >>> now = datetime.datetime(2009, 9, 28, 12, 24, 30) >>> timesince(d, now, True) u'2 days, 23 hours later' >>> now = datetime.datetime(2009, 10, 3, 12, 24, 30) >>> timesince(d, now, True) u'2 days ago'
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):<EOL><INDENT>flags = <NUM_LIT:1><EOL><DEDENT>if __CSL(link_name, source, flags) == <NUM_LIT:0>:<EOL><INDENT>raise ctypes.WinError()<EOL><DEDENT>
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 = bottom or border.bottom<EOL>return Border(top=top, left=left, right=right, bottom=bottom)<EOL><DEDENT>cell.alignment = alignment<EOL>cell.fill = fill<EOL>rows = list(self.sheet[cell_range])<EOL>for cell in rows[<NUM_LIT:0>]:<EOL><INDENT>cell.border = border_add(cell.border, top=top)<EOL><DEDENT>for cell in rows[-<NUM_LIT:1>]:<EOL><INDENT>cell.border = border_add(cell.border, bottom=bottom)<EOL><DEDENT>for row in rows:<EOL><INDENT>l = row[<NUM_LIT:0>]<EOL>r = row[-<NUM_LIT:1>]<EOL>l.border = border_add(l.border, left=left)<EOL>r.border = border_add(r.border, right=right)<EOL><DEDENT>
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><INDENT>row = {'<STR_LIT>':cell.value[<NUM_LIT:6>:-<NUM_LIT:2>].strip(), '<STR_LIT>':[], '<STR_LIT>':[]}<EOL>top.append(row)<EOL>top = row['<STR_LIT>']<EOL>stack.append(top)<EOL>if self.begin == <NUM_LIT:1>:<EOL><INDENT>self.begin = i<EOL><DEDENT><DEDENT>elif (isinstance(cell.value, str) and<EOL>cell.value == '<STR_LIT>'):<EOL><INDENT>stack.pop()<EOL>top = stack[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>row = {'<STR_LIT>':[], '<STR_LIT>':[]}<EOL>cols = row['<STR_LIT>']<EOL>for j in range(<NUM_LIT:1>, self.sheet.max_column+<NUM_LIT:1>):<EOL><INDENT>cell = self.sheet.cell(row=i, column=j)<EOL>v = self.process_cell(i, j, cell)<EOL>if v:<EOL><INDENT>cols.append(v)<EOL><DEDENT><DEDENT>if row['<STR_LIT>'] or row['<STR_LIT>']:<EOL><INDENT>top.append(row)<EOL><DEDENT><DEDENT><DEDENT>return rows<EOL>
读取一个Excel模板,将此Excel的所有行读出来,并且识别特殊的标记进行记录 :return: 返回读取后的模板,结果类似: [ {'cols': #各列,与subs不会同时生效 'subs':[ #子模板 {'cols':#各列, 'subs': #子模板 'field': #对应数据中字段名称 }, ... ] 'field': #对应数据中字段名称 }, ... ] 子模板的判断根据第一列是否为 {{for field}} 来判断,结束使用 {{end}}
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, [{}])<EOL>_subs(sheet, line['<STR_LIT>'], d)<EOL><DEDENT>else:<EOL><INDENT>self.write_line(sheet, line, data)<EOL><DEDENT><DEDENT>
: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 text or (text and not (text.startswith('<STR_LIT>') and text.endswith('<STR_LIT>'))<EOL>and row[c['<STR_LIT>']-<NUM_LIT:1>].value == text):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
匹配一个模板时,只比较起始行,未来考虑支持比较关键字段即可,现在是起始行的所有字段全匹配 :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_line['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']:<EOL><INDENT>if c['<STR_LIT>']:<EOL><INDENT>cell = row[c['<STR_LIT>']-<NUM_LIT:1>]<EOL>if isinstance(cell.value, str):<EOL><INDENT>v = cell.value.strip()<EOL><DEDENT>else:<EOL><INDENT>v = cell.value<EOL><DEDENT>d[c['<STR_LIT>']] = v<EOL><DEDENT><DEDENT>yield d<EOL><DEDENT>
用于简单模板匹配,只处理一行的模板, 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("<STR_LIT>".format(type(input_file)))<EOL><DEDENT>self.result = None<EOL>self.callback = callback<EOL>if use_merge:<EOL><INDENT>self.merge = Merge(keys=merge_keys, left_join=merge_left_join, verbose=merge_verbose)<EOL><DEDENT>else:<EOL><INDENT>self.merge = False<EOL><DEDENT>template = self.get_template()<EOL>self.result = self.read(template, find=find, begin=begin)<EOL>if self.callback:<EOL><INDENT>self.callback(self.result)<EOL><DEDENT>
: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 to combine multiple data :param merge_keys: keys parameter used in Merge :param merge_left_join: left_join parameter used in Merge :param merge_verbose: verbose parameter used in Merge :param find: 是否查找模板,缺省为False :param begin: 是否从begin行开始,缺省为1 :param callback: callback function used after combine data, the callback function should be: ``` def func(row_data): ``` :return:
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)<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>
: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_comment = r'<STR_LIT>'<EOL>space_comment = r'<STR_LIT>'<EOL>string1 =r'<STR_LIT>'<EOL>string2 = r'<STR_LIT>'<EOL>strings = r'<STR_LIT>' % (string1, string2)<EOL>charclass = r'<STR_LIT>'<EOL>nospecial = r'<STR_LIT>'<EOL>regex = r'<STR_LIT>' % (<EOL>nospecial, charclass, nospecial<EOL>)<EOL>space = r'<STR_LIT>' % (space_chars, space_comment)<EOL>newline = r'<STR_LIT>' % line_comment<EOL>def fix_charclass(result):<EOL><INDENT>"""<STR_LIT>"""<EOL>pos = result.find('<STR_LIT:->')<EOL>if pos >= <NUM_LIT:0>:<EOL><INDENT>result = r'<STR_LIT>' % (result[:pos], result[pos + <NUM_LIT:1>:])<EOL><DEDENT>def sequentize(string):<EOL><INDENT>"""<STR_LIT>"""<EOL>first, last, result = None, None, []<EOL>for char in map(ord, string):<EOL><INDENT>if last is None:<EOL><INDENT>first = last = char<EOL><DEDENT>elif last + <NUM_LIT:1> == char:<EOL><INDENT>last = char<EOL><DEDENT>else:<EOL><INDENT>result.append((first, last))<EOL>first = last = char<EOL><DEDENT><DEDENT>if last is not None:<EOL><INDENT>result.append((first, last))<EOL><DEDENT>return '<STR_LIT>'.join(['<STR_LIT>' % (<EOL>chr(first),<EOL>last > first + <NUM_LIT:1> and '<STR_LIT:->' or '<STR_LIT>',<EOL>last != first and chr(last) or '<STR_LIT>'<EOL>) for first, last in result])<EOL><DEDENT>return _re.sub(r'<STR_LIT>', <EOL>lambda m: '<STR_LIT>' % ord(m.group(<NUM_LIT:1>)), (sequentize(result)<EOL>.replace('<STR_LIT:\\>', '<STR_LIT>')<EOL>.replace('<STR_LIT:[>', '<STR_LIT>')<EOL>.replace('<STR_LIT:]>', '<STR_LIT>')<EOL>)<EOL>)<EOL><DEDENT>def id_literal_(what):<EOL><INDENT>"""<STR_LIT>"""<EOL>match = _re.compile(what).match<EOL>result = '<STR_LIT>'.join([<EOL>chr(c) for c in xrange(<NUM_LIT>) if not match(chr(c))<EOL>])<EOL>return '<STR_LIT>' % fix_charclass(result)<EOL><DEDENT>def not_id_literal_(keep):<EOL><INDENT>"""<STR_LIT>"""<EOL>match = _re.compile(id_literal_(keep)).match<EOL>result = '<STR_LIT>'.join([<EOL>chr(c) for c in xrange(<NUM_LIT>) if not match(chr(c))<EOL>])<EOL>return r'<STR_LIT>' % fix_charclass(result)<EOL><DEDENT>not_id_literal = not_id_literal_(r'<STR_LIT>')<EOL>preregex1 = r'<STR_LIT>'<EOL>preregex2 = r'<STR_LIT>' % locals()<EOL>id_literal = id_literal_(r'<STR_LIT>')<EOL>id_literal_open = id_literal_(r'<STR_LIT>')<EOL>id_literal_close = id_literal_(r'<STR_LIT>')<EOL>space_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>) % locals()).sub<EOL>def space_subber(match):<EOL><INDENT>"""<STR_LIT>"""<EOL>groups = match.groups()<EOL>if groups[<NUM_LIT:0>]: return groups[<NUM_LIT:0>]<EOL>elif groups[<NUM_LIT:1>]: return groups[<NUM_LIT:1>]<EOL>elif groups[<NUM_LIT:2>]: return groups[<NUM_LIT:2>]<EOL>elif groups[<NUM_LIT:3>]: return groups[<NUM_LIT:3>]<EOL>elif groups[<NUM_LIT:4>]: return '<STR_LIT:\n>'<EOL>elif groups[<NUM_LIT:5>] or groups[<NUM_LIT:6>] or groups[<NUM_LIT:7>]: return '<STR_LIT:U+0020>'<EOL>else: return '<STR_LIT>'<EOL><DEDENT>def jsmin(script): <EOL><INDENT>r"""<STR_LIT>"""<EOL>return space_sub(space_subber, '<STR_LIT>' % script).strip()<EOL><DEDENT>return jsmin<EOL>
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>] and '<STR_LIT:U+0020>') or<EOL>(groups[<NUM_LIT:7>] and '<STR_LIT:U+0020>') or<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>return _re.sub(<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>r'<STR_LIT>'<EOL>r'<STR_LIT>', subber, '<STR_LIT>' % script<EOL>).strip()<EOL>
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 :Warning: This function is the digest of a _make_jsmin() call. It just utilizes the resulting regex. It's just for fun here and may vanish any time. Use the `jsmin` function instead. :Parameters: `script` : ``str`` Script to minify :Return: Minified script :Rtype: ``str``
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` objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of :class:`FormDataParser`. Have a look at :ref:`dealing-with-request-data` for more details. .. versionadded:: 0.5 The `max_form_memory_size`, `max_content_length` and `cls` parameters were added. .. versionadded:: 0.5.1 The optional `silent` flag was added. :param environ: the WSGI environment to be used for parsing. :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works the same as :meth:`~BaseResponse._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param max_content_length: If this is provided and the transmitted data is longer than this value an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param silent: If set to False parsing errors will not be caught. :return: A tuple in the form ``(stream, form, files)``.
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.read(<NUM_LIT> * <NUM_LIT:64>)<EOL>if not chunk:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return update_wrapper(wrapper, f)<EOL>
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 = result[-<NUM_LIT:1>]<EOL>result[-<NUM_LIT:1>] = (key, value + '<STR_LIT>' + line[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>parts = line.split('<STR_LIT::>', <NUM_LIT:1>)<EOL>if len(parts) == <NUM_LIT:2>:<EOL><INDENT>result.append((parts[<NUM_LIT:0>].strip(), parts[<NUM_LIT:1>].strip()))<EOL><DEDENT><DEDENT><DEDENT>return Headers(result)<EOL>
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:<EOL><INDENT>try:<EOL><INDENT>return parse_func(self, stream, mimetype,<EOL>content_length, options)<EOL><DEDENT>except ValueError:<EOL><INDENT>if not self.silent:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>return stream, self.cls(), self.cls()<EOL>
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 (used for the multipart boundary for instance) :return: A tuple in the form ``(stream, form, files)``.
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 terminator != next_part:<EOL><INDENT>self.fail('<STR_LIT>')<EOL><DEDENT>while terminator != last_part:<EOL><INDENT>headers = parse_multipart_headers(iterator)<EOL>disposition = headers.get('<STR_LIT>')<EOL>if disposition is None:<EOL><INDENT>self.fail('<STR_LIT>')<EOL><DEDENT>disposition, extra = parse_options_header(disposition)<EOL>transfer_encoding = self.get_part_encoding(headers)<EOL>name = extra.get('<STR_LIT:name>')<EOL>filename = extra.get('<STR_LIT:filename>')<EOL>if filename is None:<EOL><INDENT>yield _begin_form, (headers, name)<EOL><DEDENT>else:<EOL><INDENT>yield _begin_file, (headers, name, filename)<EOL><DEDENT>buf = b'<STR_LIT>'<EOL>for line in iterator:<EOL><INDENT>if not line:<EOL><INDENT>self.fail('<STR_LIT>')<EOL><DEDENT>if line[:<NUM_LIT:2>] == b'<STR_LIT>':<EOL><INDENT>terminator = line.rstrip()<EOL>if terminator in (next_part, last_part):<EOL><INDENT>break<EOL><DEDENT><DEDENT>if transfer_encoding is not None:<EOL><INDENT>if transfer_encoding == '<STR_LIT>':<EOL><INDENT>transfer_encoding = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>line = codecs.decode(line, transfer_encoding)<EOL><DEDENT>except Exception:<EOL><INDENT>self.fail('<STR_LIT>')<EOL><DEDENT><DEDENT>if buf:<EOL><INDENT>yield _cont, buf<EOL>buf = b'<STR_LIT>'<EOL><DEDENT>if line[-<NUM_LIT:2>:] == b'<STR_LIT:\r\n>':<EOL><INDENT>buf = b'<STR_LIT:\r\n>'<EOL>cutoff = -<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>buf = line[-<NUM_LIT:1>:]<EOL>cutoff = -<NUM_LIT:1><EOL><DEDENT>yield _cont, line[:cutoff]<EOL><DEDENT>else: <EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if buf not in (b'<STR_LIT>', b'<STR_LIT:\r>', b'<STR_LIT:\n>', b'<STR_LIT:\r\n>'):<EOL><INDENT>yield _cont, buf<EOL><DEDENT>yield _end, None<EOL><DEDENT>
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 = container.write<EOL><DEDENT>elif ellt == _begin_form:<EOL><INDENT>headers, name = ell<EOL>is_file = False<EOL>container = []<EOL>_write = container.append<EOL>guard_memory = self.max_form_memory_size is not None<EOL><DEDENT>elif ellt == _cont:<EOL><INDENT>_write(ell)<EOL>if guard_memory:<EOL><INDENT>in_memory += len(ell)<EOL>if in_memory > self.max_form_memory_size:<EOL><INDENT>self.in_memory_threshold_reached(in_memory)<EOL><DEDENT><DEDENT><DEDENT>elif ellt == _end:<EOL><INDENT>if is_file:<EOL><INDENT>container.seek(<NUM_LIT:0>)<EOL>yield ('<STR_LIT:file>',<EOL>(name, FileStorage(container, filename, name,<EOL>headers=headers)))<EOL><DEDENT>else:<EOL><INDENT>part_charset = self.get_part_charset(headers)<EOL>yield ('<STR_LIT>',<EOL>(name, b'<STR_LIT>'.join(container).decode(<EOL>part_charset, self.errors)))<EOL><DEDENT><DEDENT><DEDENT>
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 arguments.
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><DEDENT>try:<EOL><INDENT>import memcache<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return memcache.Client(servers)<EOL><DEDENT>
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 key, converter in iteritems(rule._converters):<EOL><INDENT>js_func = js_to_url_function(converter)<EOL>try:<EOL><INDENT>index = converters.index(js_func)<EOL><DEDENT>except ValueError:<EOL><INDENT>converters.append(js_func)<EOL>index = len(converters) - <NUM_LIT:1><EOL><DEDENT>rule_converters[key] = index<EOL><DEDENT>rules.append({<EOL>u'<STR_LIT>': rule.endpoint,<EOL>u'<STR_LIT>': list(rule.arguments),<EOL>u'<STR_LIT>': rule_converters,<EOL>u'<STR_LIT>': trace,<EOL>u'<STR_LIT>': rule.defaults<EOL>})<EOL><DEDENT>return render_template(name_parts=name and name.split('<STR_LIT:.>') or [],<EOL>rules=dumps(rules),<EOL>converters=converters)<EOL>
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 names are resolved (so you an use a name like 'obj.url_for') In order to use JavaScript generation, simplejson must be installed. Note that using this feature will expose the rules defined in your map to users. If your rules contain sensitive information, don't use JavaScript generation!
f5854:m1