Redis基础 - Redis数据库基础、python操作Red

2018-11-23  本文已影响0人  莫名ypc

Redis

list
添加元素和删除元素只能在最后一个位置进行 -- 栈

添加元素只能在最后一个位置进行 删除元素只能在第一个位置进行 -- 队列

python操作Redis数据库

序列化 - 把对象转换成字节或者字符序列 - 串行化 / 腌咸菜 - serialize
反序列化 - 把字节或者字符序列还原成对象 - 反串行化 - deserialize
json模块 - 字符串形式(字符)的序列化和反序列化

import pickle

import redis


class Student(object):

    def __init__(self, name, age):
        self.name = name
        self.age = age


def main():
    client = redis.StrictRedis(host='47.107.174.141',
                               password=123456)
    client.set('username', 'hellokitty', 120)
    print(client.ttl('username'))
    print(client.get('username'))
    print(client.expire('username', 300))
    print(client.ttl('username'))
    stu1 = Student('haha', 20)
    # client.hset('stu', 'name', stu1.name)
    # client.hset('stu', 'age', stu1.age)
    client.set('stu', pickle.dumps(stu1))


if __name__ == '__main__':
    main()
import pickle
import redis


class Student(object):

    def __init__(self, name, age):
        self.name = name
        self.age = age


def main():
    client = redis.StrictRedis(host='47.107.174.141',
                               password=123456)
    stu = pickle.loads(client.get('stu'))
    print(stu.name)
    print(stu.age)


if __name__ == '__main__':
    main()

base64编码数据、python连接Redis数据库进行存取

import base64
import redis


def main():
    client = redis.StrictRedis(host='47.107.174.141',
                               password=123456)
    with open('img/p1.jpg', 'rb') as f:
        photo = base64.b64encode(f.read())
        print(photo)
        client.set('photo', photo)


if __name__ == '__main__':
    main()
import base64
import redis


def main():
    client = redis.StrictRedis(host='47.107.174.141',
                               password=123456)
    photo = client.get('photo')
    with open('img/p2.jpg', 'wb') as f:
        f.write(base64.b64decode(photo))


if __name__ == '__main__':
    main()
上一篇 下一篇

猜你喜欢

热点阅读