允许混合字符串和字节而无需猜测的bencoder
typed-bencode的Python项目详细描述
键入dbencode
使创建对象的圆形可折叠梯段变得容易。
用法
importtyped_bencodefromtypingimportListmy_type=typed_bencode.for_dict(a=str,b=int,c=bytes,d=List[str])val={"a":"hello","b":123,"c":b'asd',"d":["hey","there"]}encoded=my_type.encode(val)print(encoded)# => b'd1:a5:hello1:bi123e1:c3:asd1:dl3:hey5:thereee'print(my_type.decode(encoded)==val)# => True
您甚至可以编写类型
my_other_type=typed_bencode.for_dict(a=my_type,b=int)encoded2=my_other_type.encode({"a":{"a":"helo","b":123,"c":b'asd',"d":["asd","asd"]},"b":123})print(encoded2)# => b'd1:ad1:a4:helo1:bi123e1:c3:asd1:dl3:asd3:asdee1:bi123ee'
自定义类型
您可以指定自定义类型
classDateEncoder(typed_bencode.StringEncoder):defto_bytes(self,val):returnsuper().to_bytes(val.isoformat())classDateDecoder(typed_bencode.StringDecoder):deffrom_bytes(self,b):v,pos=super().from_bytes(b)return(datetime.datetime.fromisoformat(v),pos)classDateType(typed_bencode.BaseType):def__init__(self):super().__init__()self.encoder=DateEncoder(self)self.decoder=DateDecoder(self)my_type=DateType()val=datetime.datetime.now()encoded=my_type.encode(val)# => '26:2018-06-06T12:12:12.363636'