1. 程式人生 > 實用技巧 >Python基礎(7)——redis、加密(md5、base64)、介面開發、網路程式設計

Python基礎(7)——redis、加密(md5、base64)、介面開發、網路程式設計

正文

一、redis

1、安裝模組:

pip install redis

2、連線redis

插入key-value,查詢

import redis
r=redis.Redis(
    host='127.0.0.1',
    password='123456',
    port=6379,
    db=0
)
r.set('stu123','abc666') #v只能字串
r.set('prod','{"price":1.1,"count":6}')
print(r.get('prod'))

3、位元組型別 <---轉換--> 字串

print(r.get('
prod'))#b'{"price":1.1,"count":6}' #bytes 位元組型別 # f=open('a.jpg','wb') #bytes data=r.get('prod') print(data.decode()) #bytes 位元組型別轉換成字串 s='你好' print(s.encode())#變成bytes型別

4、刪除key

print(r.get('prod'))#b'{"price":1.1,"count":6}'
r.delete('prod')   #刪除

5、過期時間

r.set('prod','123')
expire_time = 60*60*24  #
過期時間 單位s r.set('fd_session','sdgx312vsdrq',expire_time)

6、雜湊型別

1)插入資料、查詢

r.hset('student','fd','{"money:9999"}')
r.hset('student','ds','{"money:991299"}')
r.hset('student','lhy','{"money:99449"}')

print(r.hget('student','ds'))
print(r.hgetall('student'))

2)刪除

#hash
r.hset('student','fd','
{"money:9999"}') r.hset('student','ds','{"money:991299"}') r.hset('student','lhy','{"money:99449"}') print(r.hget('student','ds')) print(r.hgetall('student')) r.expire('student',100)#指定某個key的過期時間 r.hdel('student','ds') #刪除hash中某個key

3)轉化為字典

#轉化為字典
d= r.hgetall('student')
new_d={}
for k,v in d.items():
    new_d[k.decode()]=v.decode()
print(new_d)

#其他方法:
#當新增加引數decode_responses=True返回的直接就是字典 # r=redis.Redis( # host='118.24.3.40', # password='HK139bc&*', # port=6379, # db=0, # decode_responses=True # )

4)其他方法

print(r.keys())
print(r.keys('s*'))
print(r.type('stu'))
print(r.type('student'))
# print(r.flushdb())#清空當前資料庫所有key
# print(r.flushall())#清空所有資料庫所有key
# print(r.exists('abc'))#判斷某個key是否存在

5)管道

print(r.get('prod'))#b'{"price":1.1,"count":6}' #bytes 位元組型別 # f=open('a.jpg','wb') #bytes data=r.get('prod') print(data.decode()) #bytes 位元組型別轉換成字串 s='你好' print(s.encode())#變成bytes型別