文章目录
概述
codecs:这个模块定义了标准 Python 编解码器(编码器和解码器)的基类,并提供接口用来访问内部的 Python 编解码器注册表,该注册表负责管理编解码器和错误处理的查找过程。 大多数标准编解码器都属于 文本编码,它们可将文本编码为字节串,但也提供了一些编解码器可将文本编码为文本,以及字节串编码为字节串。 自定义编解码器可以在任意类型间进行编码和解码,但某些模块特性仅适用于 文本编码或将数据编码为 字节串 的编解码器。
Python3.5 使用 protobuf3.0.0.beta2
该模块定义了以下用于使用任何编解码器进行编码和解码的函数:
# 使用为 encoding 注册的编解码器对 obj 进行编码 可以给定 Errors 以设置所需要的错误处理方案。 codecs.encode(obj, encoding='utf-8', errors='strict') # 使用为 encoding 注册的编解码器对 obj 进行解码 可以给定 Errors 以设置所需要的错误处理方案。 codecs.decode(obj, encoding='utf-8', errors='strict') # 每种编解码器的完整细节也可以直接查找获取 在 Python 编解码器注册表中查找编解码器信息,并返回一个 CodecInfo 对象, codecs.lookup(encoding) # 查找编解码器注册表所得到的编解码器细节信息 class CodecInfo(tuple): _is_text_encoding = True # Assume codecs are text encodings by default def __new__(cls, encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None, *, _is_text_encoding=None): self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter)) self.name = name self.encode = encode self.decode = decode self.incrementalencoder = incrementalencoder self.incrementaldecoder = incrementaldecoder self.streamwriter = streamwriter self.streamreader = streamreader if _is_text_encoding is not None: self._is_text_encoding = _is_text_encoding return self def __repr__(self): return "<%s.%s object for encoding %s at %#x>" % \ (self.__class__.__module__, self.__class__.__qualname__, self.name, id(self)) # 为了简化对各种编解码器组件的访问,本模块提供了以下附加函数,它们使用 lookup() 来执行编解码器查找: # 查找给定编码的编解码器并返回其编码器函数。 codecs.getencoder(encoding) # 查找给定编码的编解码器并返回其解码器函数。 codecs.getdecoder(encoding) # 查找给定编码的编解码器并返回其增量式编码器类或工厂函数。 codecs.getincrementalencoder(encoding) # 查找给定编码的编解码器并返回其增量式解码器类或工厂函数。 codecs.getincrementaldecoder(encoding) # 查找给定编码的编解码器并返回其 StreamReader 类或工厂函数。 codecs.getreader(encoding) # 查找给定编码的编解码器并返回其 StreamWriter 类或工厂函数。 codecs.getwriter(encoding) # 自定义编解码器的启用是通过注册适当的编解码器搜索函数: # 注册一个编解码器搜索函数。 搜索函数预期接收一个参数,即全部以小写字母表示的编码名称,并返回一个 CodecInfo 对象。 在搜索函数无法找到给定编码的情况下,它应当返回 None codecs.register(search_function) # 常量 codecs.BOM codecs.BOM_BE codecs.BOM_LE codecs.BOM_UTF8 codecs.BOM_UTF16 codecs.BOM_UTF16_BE codecs.BOM_UTF16_LE¶ codecs.BOM_UTF32 codecs.BOM_UTF32_BE codecs.BOM_UTF32_LE
以上是源码部分的简单介绍,详细的内容博主建议可以去python官方源码文档中阅读,详情点击
谈谈我在何处用到这个模块
response = HttpResponse(content_type='text/csv') field_list = exportable_fields response['Content-Disposition'] = 'attachment;filename=%s.csv' % ( datetime.now().strftime('%Y-%m-%d-%H-%M-%S')) response.write(codecs.BOM_UTF8)
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/219337.html原文链接:https://javaforall.net
