Exemplo n.º 1
0
    def __init__(self, color=True, fmt=DEFAULT_FORMAT,
                 datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):
        r"""
        :arg bool color: Enables color support.
        :arg string fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(normal)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg string datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._fmt = fmt

        self._colors = {}
        if color and _stderr_supports_color():
            # The curses module has some str/bytes confusion in
            # python3.  Until version 3.2.3, most methods return
            # bytes, but only accept strings.  In addition, we want to
            # output these strings with the logging module, which
            # works with unicode strings.  The explicit calls to
            # unicode() below are harmless in python2 but will do the
            # right conversion in python 3.
            fg_color = (curses.tigetstr("setaf") or
                        curses.tigetstr("setf") or "")
            if (3, 0) < sys.version_info < (3, 2, 3):
                fg_color = unicode_type(fg_color, "ascii")

            for levelno, code in colors.items():
                self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii")
            self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
        else:
            self._normal = ''
Exemplo n.º 2
0
    def __init__(
        self,
        fmt: str = DEFAULT_FORMAT,
        datefmt: str = DEFAULT_DATE_FORMAT,
        style: str = "%",
        color: bool = True,
        colors: Dict[int, int] = DEFAULT_COLORS,
    ) -> None:
        r"""
        :arg bool color: Enables color support.
        :arg str fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(end_color)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg str datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``fmt`` and ``datefmt`` arguments.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._fmt = fmt

        self._colors = {}  # type: Dict[int, str]
        if color and _stderr_supports_color():
            if curses is not None:
                fg_color = curses.tigetstr("setaf") or curses.tigetstr("setf") or b""

                for levelno, code in colors.items():
                    # Convert the terminal control characters from
                    # bytes to unicode strings for easier use with the
                    # logging module.
                    self._colors[levelno] = unicode_type(
                        curses.tparm(fg_color, code), "ascii"
                    )
                normal = curses.tigetstr("sgr0")
                if normal is not None:
                    self._normal = unicode_type(normal, "ascii")
                else:
                    self._normal = ""
            else:
                # If curses is not present (currently we'll only get here for
                # colorama on windows), assume hard-coded ANSI color codes.
                for levelno, code in colors.items():
                    self._colors[levelno] = "\033[2;3%dm" % code
                self._normal = "\033[0m"
        else:
            self._normal = ""
Exemplo n.º 3
0
    def __init__(self,
                 fmt=DEFAULT_FORMAT,
                 datefmt=DEFAULT_DATE_FORMAT,
                 style='%',
                 color=True,
                 colors=DEFAULT_COLORS):
        r"""
        :arg bool color: Enables color support.
        :arg string fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(end_color)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg string datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``fmt`` and ``datefmt`` arguments.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._fmt = fmt

        self._colors = {}
        if color and _stderr_supports_color():
            if curses is not None:
                # The curses module has some str/bytes confusion in
                # python3.  Until version 3.2.3, most methods return
                # bytes, but only accept strings.  In addition, we want to
                # output these strings with the logging module, which
                # works with unicode strings.  The explicit calls to
                # unicode() below are harmless in python2 but will do the
                # right conversion in python 3.
                fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf")
                            or "")
                if (3, 0) < sys.version_info < (3, 2, 3):
                    fg_color = unicode_type(fg_color, "ascii")

                for levelno, code in colors.items():
                    self._colors[levelno] = unicode_type(
                        curses.tparm(fg_color, code), "ascii")
                self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
            elif sys.stderr is getattr(colorama, 'wrapped_stderr', object()):
                for levelno, code in colors.items():
                    self._colors[levelno] = '\033[2;3%dm' % code
                self._normal = '\033[0m'
            else:
                raise RuntimeError("No supported color terminal library")
        else:
            self._normal = ''
Exemplo n.º 4
0
    def url_unescape(value, encoding='utf-8', plus=True):
        """Decodes the given value from a URL.

        The argument may be either a byte or unicode string.

        If encoding is None, the result will be a byte string.  
        
        Otherwise,
        the result is a unicode string in the specified encoding.

        If ``plus`` is true (the default), plus signs will be interpreted
        as spaces (literal plus signs must be represented as "%2B").  This
        is appropriate for query strings and form-encoded values 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
        """
        unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
        if encoding is None:
            return unquote(utf8(value))
        else:
            return unicode_type(unquote(utf8(value)), encoding)
Exemplo n.º 5
0
    def url_unescape(value, encoding='utf-8', plus=True):
        """
        Decodes the given value from a URL.

        The argument may be either a byte or unicode string.

        If encoding is None, the result will be a byte string.  
        
        Otherwise, the result is a unicode string in the specified encoding.

        If ``plus`` is true (the default), plus signs will be interpreted
        as spaces (literal plus signs must be represented as "%2B").  This
        is appropriate for query strings and form-encoded values 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
        """
        unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
        if encoding is None:
            return unquote(utf8(value))
        else:
            return unicode_type(unquote(utf8(value)), encoding)
Exemplo n.º 6
0
def converter_default(data):
    length = data.find('/')
    if length == 1 or len(data) == 0:
        raise NoMatchError()
    elif length < 0:
        length = len(data)
    return length, util.unicode_type(data[:length])
Exemplo n.º 7
0
    def check_info(self, user):
        if not user:
            return self.send_error(errors.incomplete)
        if not user.email:
            return self.send_error(errors.need_email)
        if not user.name:
            return self.send_error(errors.incomplete, reason='姓名')
        if not user.password:
            return self.send_error(errors.need_password)

        user.email = user.email.lower()
        if not re_email.match(user.email):
            return self.send_error(errors.invalid_email)
        if not re_password.match(user.password) or re.match(
                r'^(\d+|[A-Z]+|[a-z]+)$', user.password):
            return self.send_error(errors.invalid_psw_format)

        if not re_name.match(unicode_type(user.name)):
            return self.send_error(errors.invalid_name, reason=user.name)

        user.id = errors.gen_id(user.email, 'user')
        user.create_time = errors.get_date_time()
        self.authority = user.authority = ''

        return True
Exemplo n.º 8
0
    def __init__(
        self,
        fmt: str = DEFAULT_FORMAT,
        datefmt: str = DEFAULT_DATE_FORMAT,
        style: str = "%",
        color: bool = True,
        colors: Dict[int, int] = DEFAULT_COLORS,
    ) -> None:
        r"""
        :arg bool color: Enables color support.
        :arg str fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(end_color)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg str datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``fmt`` and ``datefmt`` arguments.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._fmt = fmt

        self._colors = {}  # type: Dict[int, str]
        if color and _stderr_supports_color():
            if curses is not None:
                fg_color = curses.tigetstr("setaf") or curses.tigetstr("setf") or b""

                for levelno, code in colors.items():
                    # Convert the terminal control characters from
                    # bytes to unicode strings for easier use with the
                    # logging module.
                    self._colors[levelno] = unicode_type(
                        curses.tparm(fg_color, code), "ascii"
                    )
                self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
            else:
                # If curses is not present (currently we'll only get here for
                # colorama on windows), assume hard-coded ANSI color codes.
                for levelno, code in colors.items():
                    self._colors[levelno] = "\033[2;3%dm" % code
                self._normal = "\033[0m"
        else:
            self._normal = ""
Exemplo n.º 9
0
 def get_path(self, values=None):
     if values is None:
         values = {}
     re = []
     for converter, args, data in self.route:
         if converter:
             re.append(util.unicode_type(values[data]))
         else:
             re.append(data)
     return ''.join(re)
Exemplo n.º 10
0
    def check(self):
        self.current_user = self.get_current_user()
        if not self.current_user:
            return self.send_error(errors.need_login)

        info = self.get_body_obj(u.User)
        if not info or not info.email:
            return self.send_error(errors.incomplete)
        if info.name and not re_name.match(unicode_type(info.name)):
            return self.send_error(errors.invalid_name)

        return info
Exemplo n.º 11
0
    def url_unescape(value, encoding='utf-8'):
        """Decodes the given value from a URL.

        The argument may be either a byte or unicode string.

        If encoding is None, the result will be a byte string.  Otherwise,
        the result is a unicode string in the specified encoding.
        """
        if encoding is None:
            return urllib_parse.unquote_plus(utf8(value))
        else:
            return unicode_type(urllib_parse.unquote_plus(utf8(value)), encoding)
Exemplo n.º 12
0
 def __init__(self, color=True, *args, **kwargs):
     logging.Formatter.__init__(self, *args, **kwargs)
     self._color = color and _stderr_supports_color()
     if self._color:
         # The curses module has some str/bytes confusion in
         # python3. Until version 3.2.3, most methods return
         # bytes, but only accept strings. In addition, we want to
         # output these strings with the logging module, which
         # works with unicode strings. The explicit calls to
         # unicode() below are harmless in python2 but will do the
         # right conversion in python 3.
         fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf")
                     or "")
         if (3, 0) < sys.version_info < (3, 2, 3):
             fg_color = unicode_type(fg_color, "ascii")
         self._colors = {
             logging.DEBUG:
             unicode_type(
                 curses.tparm(fg_color, 4),  # Blue
                 "ascii"),
             logging.INFO:
             unicode_type(
                 curses.tparm(fg_color, 2),  # Green
                 "ascii"),
             logging.WARNING:
             unicode_type(
                 curses.tparm(fg_color, 3),  # Yellow
                 "ascii"),
             logging.ERROR:
             unicode_type(
                 curses.tparm(fg_color, 1),  # Red
                 "ascii"),
         }
         self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
Exemplo n.º 13
0
 def __init__(self, color=True, *args, **kwargs):
     logging.Formatter.__init__(self, *args, **kwargs)
     self._color = color and _stderr_supports_color()
     if self._color:
         # The curses module has some str/bytes confusion in
         # python3.  Until version 3.2.3, most methods return
         # bytes, but only accept strings.  In addition, we want to
         # output these strings with the logging module, which
         # works with unicode strings.  The explicit calls to
         # unicode() below are harmless in python2 but will do the
         # right conversion in python 3.
         fg_color = (curses.tigetstr("setaf") or
                     curses.tigetstr("setf") or "")
         if (3, 0) < sys.version_info < (3, 2, 3):
             fg_color = unicode_type(fg_color, "ascii")
         self._colors = {
             logging.DEBUG: unicode_type(curses.tparm(fg_color, 4),  # Blue
                                         "ascii"),
             logging.INFO: unicode_type(curses.tparm(fg_color, 2),  # Green
                                        "ascii"),
             logging.WARNING: unicode_type(curses.tparm(fg_color, 3),  # Yellow
                                           "ascii"),
             logging.ERROR: unicode_type(curses.tparm(fg_color, 1),  # Red
                                         "ascii"),
         }
         self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
Exemplo n.º 14
0
Arquivo: __init__.py Projeto: xoxoj/oz
    def add(self):
        """Adds the new experiment"""

        # Check to ensure the experiment doesn't already exists
        if self.exists():
            raise ExperimentException(self.name, "already exists")

        # Add the experiment
        json = dict(creation_date=util.unicode_type(datetime.datetime.now()))
        pipe = self.redis.pipeline(transaction=True)
        pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, self.name)
        pipe.hset(self._redis_key(), "metadata", escape.json_encode(json))
        pipe.execute()
Exemplo n.º 15
0
def add_experiment(redis, name):
    """Adds a new experiment"""

    if not ALLOWED_NAMES.match(name):
        raise ExperimentException(name, "Illegal name")
    if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name):
        raise ExperimentException(name, "Already exists")

    json = dict(creation_date=util.unicode_type(datetime.datetime.now()))
    pipe = redis.pipeline(transaction=True)
    pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, name)
    pipe.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % name, "metadata", escape.json_encode(json))
    pipe.execute()
    return Experiment(redis, name)
Exemplo n.º 16
0
def add_experiment(redis, name):
    """Adds a new experiment"""

    if not ALLOWED_NAMES.match(name):
        raise ExperimentException(name, "Illegal name")
    if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name):
        raise ExperimentException(name, "Already exists")

    json = dict(creation_date=util.unicode_type(datetime.datetime.now()))
    pipe = redis.pipeline(transaction=True)
    pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, name)
    pipe.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % name, "metadata",
              escape.json_encode(json))
    pipe.execute()
    return Experiment(redis, name)
Exemplo n.º 17
0
    def url_unescape(value, encoding='utf-8', plus=True):
        """解码来自于URL 的给定值.

        该参数可以是一个字节或unicode 字符串.

        如果encoding 是None , 该结果将会是一个字节串. 否则, 该结果会是
        指定编码的unicode 字符串.

        如果 ``plus`` 是true (默认值), 加号将被解释为空格(文字加号必须被
        表示为"%2B"). 这是适用于查询字符串和form-encoded 的值, 但不是URL
        的路径组件. 注意该默认设置和Python 的urllib 模块是相反的.

        .. versionadded:: 3.1
           该 ``plus`` 参数
        """
        unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
        if encoding is None:
            return unquote(utf8(value))
        else:
            return unicode_type(unquote(utf8(value)), encoding)
Exemplo n.º 18
0
    def url_unescape(value, encoding='utf-8', plus=True):
        """解码来自于URL 的给定值.

        该参数可以是一个字节或unicode 字符串.

        如果encoding 是None , 该结果将会是一个字节串. 否则, 该结果会是
        指定编码的unicode 字符串.

        如果 ``plus`` 是true (默认值), 加号将被解释为空格(文字加号必须被
        表示为"%2B"). 这是适用于查询字符串和form-encoded 的值, 但不是URL
        的路径组件. 注意该默认设置和Python 的urllib 模块是相反的.

        .. versionadded:: 3.1
           该 ``plus`` 参数
        """
        unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
        if encoding is None:
            return unquote(utf8(value))
        else:
            return unicode_type(unquote(utf8(value)), encoding)
Exemplo n.º 19
0
    def change_info(self, info, old_user, old_auth):
        sets = {
            f: info.__dict__[f]
            for f in ['name', 'phone', 'gender'] if info.__dict__.get(f)
            and info.__dict__[f] != old_user.__dict__[f]
        }
        if sets:
            if self.current_user.id != info.id and u.ACCESS_MANAGER not in self.authority:
                return self.send_error(errors.unauthorized)

            if info.name and not re_name.match(unicode_type(info.name)):
                return self.send_error(errors.invalid_name,
                                       reason=info.name) or -1

            r = self.db.user.update_one(dict(email=info.email), {'$set': sets})
            if r.modified_count:
                self.add_op_log('change_user',
                                context=','.join([info.email] +
                                                 list(sets.keys())))
                return list(sets.keys())
        return []
Exemplo n.º 20
0
 def __init__(self, color=True, prefix_fmt=None, datefmt=None):
     r"""
     :arg bool color: Enables color support
     :arg string prefix_fmt: Log message prefix format.
       Prefix is a part of the log message, directly preceding the actual
       message text.
     :arg string datefmt: Datetime format.
       Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.
     """
     self.__prefix_fmt = prefix_fmt if prefix_fmt is not None else self.DEFAULT_PREFIX_FORMAT
     datefmt = datefmt if datefmt is not None else self.DEFAULT_DATE_FORMAT
     logging.Formatter.__init__(self, datefmt=datefmt)
     self._color = color and _stderr_supports_color()
     if self._color:
         # The curses module has some str/bytes confusion in
         # python3.  Until version 3.2.3, most methods return
         # bytes, but only accept strings.  In addition, we want to
         # output these strings with the logging module, which
         # works with unicode strings.  The explicit calls to
         # unicode() below are harmless in python2 but will do the
         # right conversion in python 3.
         fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf")
                     or "")
         if (3, 0) < sys.version_info < (3, 2, 3):
             fg_color = unicode_type(fg_color, "ascii")
         self._colors = {
             logging.DEBUG:
             unicode_type(
                 curses.tparm(fg_color, 4),  # Blue
                 "ascii"),
             logging.INFO:
             unicode_type(
                 curses.tparm(fg_color, 2),  # Green
                 "ascii"),
             logging.WARNING:
             unicode_type(
                 curses.tparm(fg_color, 3),  # Yellow
                 "ascii"),
             logging.ERROR:
             unicode_type(
                 curses.tparm(fg_color, 1),  # Red
                 "ascii"),
         }
         self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
Exemplo n.º 21
0
    def __init__(self, color=True, prefix_fmt=None, datefmt=None):
        r"""
        :arg bool color: Enables color support
        :arg string prefix_fmt: Log message prefix format.
          Prefix is a part of the log message, directly preceding the actual
          message text.
        :arg string datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``prefix_fmt`` and ``datefmt`` arguments.
        """
        self.__prefix_fmt = prefix_fmt if prefix_fmt is not None else self.DEFAULT_PREFIX_FORMAT
        datefmt = datefmt if datefmt is not None else self.DEFAULT_DATE_FORMAT
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._color = color and _stderr_supports_color()
        if self._color:
            # The curses module has some str/bytes confusion in
            # python3.  Until version 3.2.3, most methods return
            # bytes, but only accept strings.  In addition, we want to
            # output these strings with the logging module, which
            # works with unicode strings.  The explicit calls to
            # unicode() below are harmless in python2 but will do the
            # right conversion in python 3.
            fg_color = (curses.tigetstr("setaf") or
                        curses.tigetstr("setf") or "")
            if (3, 0) < sys.version_info < (3, 2, 3):
                fg_color = unicode_type(fg_color, "ascii")
            self._colors = {
                logging.DEBUG: unicode_type(curses.tparm(fg_color, 4),  # Blue
                                            "ascii"),
                logging.INFO: unicode_type(curses.tparm(fg_color, 2),  # Green
                                           "ascii"),
                logging.WARNING: unicode_type(curses.tparm(fg_color, 3),  # Yellow
                                              "ascii"),
                logging.ERROR: unicode_type(curses.tparm(fg_color, 1),  # Red
                                            "ascii"),
            }
            self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
Exemplo n.º 22
0
def converter_path(data):
    """consume rest of the path"""
    return len(data), util.unicode_type(data)
Exemplo n.º 23
0
def url_unescape(value, encoding="utf-8", plus=True):
    unquote = urllib_parse.unquote_plus if plus else urllib_parse.unquote
    if encoding is None:
        return unquote(utf8(value))
    else:
        return unicode_type(unquote(utf8(value)), encoding)
Exemplo n.º 24
0
def url_unescape(value, encoding='utf-8', plus=True):
    unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
    if encoding is None:
        return unquote(utf8(value))
    else:
        return unicode_type(unquote(utf8(value)), encoding)