CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example06.py
Views: 729
1
"""
2
编码和解码 - BASE64
3
0-9A-Za-z+/
4
1100 0101 1001 0011 0111 0110
5
00110001 00011001 00001101 00110110
6
base64
7
b64encode / b64decode
8
-------------------------------------
9
序列化和反序列化
10
序列化 - 将对象变成字节序列(bytes)或者字符序列(str) - 串行化/腌咸菜
11
反序列化 - 把字节序列或者字符序列还原成对象
12
Python标准库对序列化的支持:
13
json - 字符形式的序列化
14
pickle - 字节形式的序列化
15
dumps / loads
16
"""
17
import base64
18
import json
19
import redis
20
21
from example02 import Person
22
23
24
class PersonJsonEncoder(json.JSONEncoder):
25
26
def default(self, o):
27
return o.__dict__
28
29
30
def main():
31
cli = redis.StrictRedis(host='120.77.222.217', port=6379,
32
password='123123')
33
data = base64.b64decode(cli.get('guido'))
34
with open('guido2.jpg', 'wb') as file_stream:
35
file_stream.write(data)
36
# with open('guido.jpg', 'rb') as file_stream:
37
# result = base64.b64encode(file_stream.read())
38
# cli.set('guido', result)
39
# persons = [
40
# Person('骆昊', 39), Person('王大锤', 18),
41
# Person('白元芳', 25), Person('狄仁杰', 37)
42
# ]
43
# persons = json.loads(cli.get('persons'))
44
# print(persons)
45
# cli.set('persons', json.dumps(persons, cls=PersonJsonEncoder))
46
47
48
if __name__ == '__main__':
49
main()
50
51
52