当前位置: 首页>>代码示例>>Python>>正文


Python six.PY2属性代码示例

本文整理汇总了Python中django.utils.six.PY2属性的典型用法代码示例。如果您正苦于以下问题:Python six.PY2属性的具体用法?Python six.PY2怎么用?Python six.PY2使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在django.utils.six的用法示例。


在下文中一共展示了six.PY2属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: rfc2822_date

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def rfc2822_date(date):
    # We can't use strftime() because it produces locale-dependent results, so
    # we have to map english month and day names manually
    months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',)
    days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    # Support datetime objects older than 1900
    date = datetime_safe.new_datetime(date)
    # We do this ourselves to be timezone aware, email.Utils is not tz aware.
    dow = days[date.weekday()]
    month = months[date.month - 1]
    time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month))
    if six.PY2:             # strftime returns a byte string in Python 2
        time_str = time_str.decode('utf-8')
    if is_aware(date):
        offset = date.tzinfo.utcoffset(date)
        timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
        hour, minute = divmod(timezone, 60)
        return time_str + '%+03d%02d' % (hour, minute)
    else:
        return time_str + '-0000' 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:22,代码来源:feedgenerator.py

示例2: python_2_unicode_compatible

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def python_2_unicode_compatible(klass):
    """
    A decorator that defines __unicode__ and __str__ methods under Python 2.
    Under Python 3 it does nothing.

    To support Python 2 and 3 with a single code base, define a __str__ method
    returning text and apply this decorator to the class.
    """
    if six.PY2:
        if '__str__' not in klass.__dict__:
            raise ValueError("@python_2_unicode_compatible cannot be applied "
                             "to %s because it doesn't define __str__()." %
                             klass.__name__)
        klass.__unicode__ = klass.__str__
        klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
    return klass 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:encoding.py

示例3: base36_to_int

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def base36_to_int(s):
    """
    Converts a base 36 string to an ``int``. Raises ``ValueError` if the
    input won't fit into an int.
    """
    # To prevent overconsumption of server resources, reject any
    # base36 string that is long than 13 base36 digits (13 digits
    # is sufficient to base36-encode any 64-bit integer)
    if len(s) > 13:
        raise ValueError("Base36 input too large")
    value = int(s, 36)
    # ... then do a final check that the value will fit into an int to avoid
    # returning a long (#15067). The long type was removed in Python 3.
    if six.PY2 and value > sys.maxint:
        raise ValueError("Base36 input too large")
    return value 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:http.py

示例4: get_connection_params

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def get_connection_params(self):
        kwargs = {
            'conv': django_conversions,
            'charset': 'utf8',
        }
        if six.PY2:
            kwargs['use_unicode'] = True
        settings_dict = self.settings_dict
        if settings_dict['USER']:
            kwargs['user'] = settings_dict['USER']
        if settings_dict['NAME']:
            kwargs['db'] = settings_dict['NAME']
        if settings_dict['PASSWORD']:
            kwargs['passwd'] = force_str(settings_dict['PASSWORD'])
        if settings_dict['HOST'].startswith('/'):
            kwargs['unix_socket'] = settings_dict['HOST']
        elif settings_dict['HOST']:
            kwargs['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            kwargs['port'] = int(settings_dict['PORT'])
        # We need the number of potentially affected rows after an
        # "UPDATE", not the number of changed rows.
        kwargs['client_flag'] = CLIENT.FOUND_ROWS
        kwargs.update(settings_dict['OPTIONS'])
        return kwargs 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:27,代码来源:base.py

示例5: load_template_source

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app_config in apps.get_app_configs():
                try:
                    resource = resource_string(app_config.name, pkg_name)
                except Exception:
                    continue
                if six.PY2:
                    resource = resource.decode(self.engine.file_charset)
                return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
        raise TemplateDoesNotExist(template_name) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:eggs.py

示例6: get_system_username

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def get_system_username():
    """
    Try to determine the current system user's username.

    :returns: The username as a unicode string, or an empty string if the
        username could not be determined.
    """
    try:
        result = getpass.getuser()
    except (ImportError, KeyError):
        # KeyError will be raised by os.getpwuid() (called by getuser())
        # if there is no corresponding entry in the /etc/passwd file
        # (a very restricted chroot environment, for example).
        return ''
    if six.PY2:
        try:
            result = result.decode(DEFAULT_LOCALE_ENCODING)
        except UnicodeDecodeError:
            # UnicodeDecodeError - preventive treatment for non-latin Windows.
            return ''
    return result 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:__init__.py

示例7: register_hstore_handler

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def register_hstore_handler(connection, **kwargs):
    if connection.vendor != 'postgresql':
        return

    try:
        if six.PY2:
            register_hstore(connection.connection, globally=True, unicode=True)
        else:
            register_hstore(connection.connection, globally=True)
    except ProgrammingError:
        # Hstore is not available on the database.
        #
        # If someone tries to create an hstore field it will error there.
        # This is necessary as someone may be using PSQL without extensions
        # installed but be using other features of contrib.postgres.
        #
        # This is also needed in order to create the connection in order to
        # install the hstore extension.
        pass 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:signals.py

示例8: _create_attachment

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def _create_attachment(self, filename, content, mimetype=None):
        """
        Converts the filename, content, mimetype triple into a MIME attachment
        object.
        """
        if mimetype is None:
            mimetype, _ = mimetypes.guess_type(filename)
            if mimetype is None:
                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
        attachment = self._create_mime_attachment(content, mimetype)
        if filename:
            try:
                filename.encode('ascii')
            except UnicodeEncodeError:
                if six.PY2:
                    filename = filename.encode('utf-8')
                filename = ('utf-8', '', filename)
            attachment.add_header('Content-Disposition', 'attachment',
                                  filename=filename)
        return attachment 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:22,代码来源:message.py

示例9: get_slug

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def get_slug(text):
    def slugify(value):
        """
        same than django slugify but allowing uppercase and underscore
        """
        value = force_text(value)
        value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
        value = re.sub('[^\w\s\/_-]', '', value).strip()
        return mark_safe(re.sub('[-\s]+', '-', value))

    if PY2:
        from django.utils.encoding import force_unicode
        text = force_unicode(text)
    for sep in ('_', '/'):
        text = sep.join(slugify(t) for t in text.split(sep))
    return text.strip('/') 
开发者ID:mgaitan,项目名称:waliki,代码行数:18,代码来源:utils.py

示例10: rfc2822_date

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def rfc2822_date(date):
    # We can't use strftime() because it produces locale-dependent results, so
    # we have to map english month and day names manually
    months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',)
    days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    # Support datetime objects older than 1900
    date = datetime_safe.new_datetime(date)
    # We do this ourselves to be timezone aware, email.Utils is not tz aware.
    dow = days[date.weekday()]
    month = months[date.month - 1]
    time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month))
    if six.PY2:             # strftime returns a byte string in Python 2
        time_str = time_str.decode('utf-8')
    offset = date.utcoffset()
    # Historically, this function assumes that naive datetimes are in UTC.
    if offset is None:
        return time_str + '-0000'
    else:
        timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
        hour, minute = divmod(timezone, 60)
        return time_str + '%+03d%02d' % (hour, minute) 
开发者ID:Yeah-Kun,项目名称:python,代码行数:23,代码来源:feedgenerator.py

示例11: restart_with_reloader

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def restart_with_reloader():
    while True:
        args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv
        new_environ = os.environ.copy()
        if _win and six.PY2:
            # Environment variables on Python 2 + Windows must be str.
            encoding = get_system_encoding()
            for key in new_environ.keys():
                str_key = key.decode(encoding).encode('utf-8')
                str_value = new_environ[key].decode(encoding).encode('utf-8')
                del new_environ[key]
                new_environ[str_key] = str_value
        new_environ["RUN_MAIN"] = 'true'
        exit_code = subprocess.call(args, env=new_environ)
        if exit_code != 3:
            return exit_code 
开发者ID:Yeah-Kun,项目名称:python,代码行数:18,代码来源:autoreload.py

示例12: getargspec

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def getargspec(func):
    if six.PY2:
        return inspect.getargspec(func)

    sig = inspect.signature(func)
    args = [
        p.name for p in sig.parameters.values()
        if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
    ]
    varargs = [
        p.name for p in sig.parameters.values()
        if p.kind == inspect.Parameter.VAR_POSITIONAL
    ]
    varargs = varargs[0] if varargs else None
    varkw = [
        p.name for p in sig.parameters.values()
        if p.kind == inspect.Parameter.VAR_KEYWORD
    ]
    varkw = varkw[0] if varkw else None
    defaults = [
        p.default for p in sig.parameters.values()
        if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and p.default is not p.empty
    ] or None
    return args, varargs, varkw, defaults 
开发者ID:Yeah-Kun,项目名称:python,代码行数:26,代码来源:inspect.py

示例13: func_accepts_kwargs

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def func_accepts_kwargs(func):
    if six.PY2:
        # Not all callables are inspectable with getargspec, so we'll
        # try a couple different ways but in the end fall back on assuming
        # it is -- we don't want to prevent registration of valid but weird
        # callables.
        try:
            argspec = inspect.getargspec(func)
        except TypeError:
            try:
                argspec = inspect.getargspec(func.__call__)
            except (TypeError, AttributeError):
                argspec = None
        return not argspec or argspec[2] is not None

    return any(
        p for p in inspect.signature(func).parameters.values()
        if p.kind == p.VAR_KEYWORD
    ) 
开发者ID:Yeah-Kun,项目名称:python,代码行数:21,代码来源:inspect.py

示例14: base36_to_int

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def base36_to_int(s):
    """
    Converts a base 36 string to an ``int``. Raises ``ValueError` if the
    input won't fit into an int.
    """
    # To prevent overconsumption of server resources, reject any
    # base36 string that is longer than 13 base36 digits (13 digits
    # is sufficient to base36-encode any 64-bit integer)
    if len(s) > 13:
        raise ValueError("Base36 input too large")
    value = int(s, 36)
    # ... then do a final check that the value will fit into an int to avoid
    # returning a long (#15067). The long type was removed in Python 3.
    if six.PY2 and value > sys.maxint:
        raise ValueError("Base36 input too large")
    return value 
开发者ID:Yeah-Kun,项目名称:python,代码行数:18,代码来源:http.py

示例15: parse_cookie

# 需要导入模块: from django.utils import six [as 别名]
# 或者: from django.utils.six import PY2 [as 别名]
def parse_cookie(cookie):
    """
    Return a dictionary parsed from a `Cookie:` header string.
    """
    cookiedict = {}
    if six.PY2:
        cookie = force_str(cookie)
    for chunk in cookie.split(str(';')):
        if str('=') in chunk:
            key, val = chunk.split(str('='), 1)
        else:
            # Assume an empty name per
            # https://bugzilla.mozilla.org/show_bug.cgi?id=169091
            key, val = str(''), chunk
        key, val = key.strip(), val.strip()
        if key or val:
            # unquote using Python's algorithm.
            cookiedict[key] = http_cookies._unquote(val)
    return cookiedict 
开发者ID:Yeah-Kun,项目名称:python,代码行数:21,代码来源:cookie.py


注:本文中的django.utils.six.PY2属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。