zoukankan      html  css  js  c++  java
  • Python encode与decode完美封装

    需求:字符串转为字节,字节转为字符串,这个是网络编程最常用的需求
    注意:此代码来源Tornado源码
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import typing
    from typing import Optional, Union
    
    unicode_type = str
    
    _UTF8_TYPES = (bytes, type(None))
    @typing.overload
    def utf8(value: bytes) -> bytes:
        pass
    
    
    @typing.overload  # noqa: F811
    def utf8(value: str) -> bytes:
        pass
    
    @typing.overload  # noqa: F811
    def utf8(value: None) -> None:
        pass
    
    def utf8(value: Union[None, str, bytes], code_type='utf-8') -> Optional[bytes]:  # noqa: F811
        """ utf-8编码"""
        if isinstance(value, _UTF8_TYPES):
            return value
        if not isinstance(value, unicode_type):
            raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
        return value.encode(code_type)
    
    @typing.overload
    def to_unicode(value: str) -> str:
        pass
    
    @typing.overload  # noqa: F811
    def to_unicode(value: bytes) -> str:
        pass
    
    @typing.overload  # noqa: F811
    def to_unicode(value: None) -> None:
        pass
    
    _TO_UNICODE_TYPES = (unicode_type, type(None))
    
    def to_unicode(value: Union[None, str, bytes], code_type='utf-8') -> Optional[str]:  # noqa: F811
        """字节类型转为字符串"""
        if isinstance(value, _TO_UNICODE_TYPES):
            return value
        if not isinstance(value, bytes):
            raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
        return value.decode(code_type)
    
    if __name__ == '__main__':
        s = utf8('中国')
        print('编码:', s)
        ret = to_unicode(s)
        print('解码:', ret)
    运行结果
    编码: b'xe4xb8xadxe5x9bxbd'
    解码: 中国
  • 相关阅读:
    批量执行工具PSSH详解
    详解IPTABLES
    nginx启动脚本
    ansible离线安装
    Linux性能评估工具
    Python中路径操作
    mongodb Enable Auth
    MySQL配置参数说明
    redis未授权访问
    php反序列化笔记
  • 原文地址:https://www.cnblogs.com/ygbh/p/14023687.html
Copyright © 2011-2022 走看看