day40-Python連線Redis

weixin_34214500發表於2018-11-23

一、Redis

1.Redis資料庫

Redis記憶體資料庫 -> KV資料庫

set username hellokitty
get username

2.Redis持久化資料

Redis提供了兩種持久化資料的方案:
RDB -> 週期性將記憶體資料寫入dump檔案
AOF -> Append Only File - 把執行過的命令儲存起來

memcached
Redis - 快取(熱點資料)/ 佇列


二、Python連線Redis

1.儲存物件

"""
序列化 -> 把物件轉換成位元組或者字元序列 - 序列化 - serialize
反序列化 -> 將位元組或者字元序列還原成物件 - 反序列化 -deserialize
json模組 -> 字串形式(字元)的序列化和反序列化
dumps:將字典或者列表轉成JSON字串
loads:將JSON字串轉換成字典或者列表
pickle模組 -> 位元組形式的序列化和反序列化

"""
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.175.127',
                               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('lyh', 20)
    """
    client.hset('stu', 'name', stu1.name)
    client.hset('stu', 'age', stu1.age)
    """

    client.set('stu', pickle.dumps(stu1))


if __name__ == '__main__':
    main()

2.獲取物件

import pickle
import redis

from test1 import Student


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


if __name__ == '__main__':
    main()

3.儲存二進位制檔案

import base64
import redis

from test1 import Student


def main():
    client = redis.StrictRedis(host='47.107.175.127',
                               password='123456')
    with open('touxiang.jpg', 'rb') as f:
        photo = base64.b64encode(f.read())
        client.set('photo', photo)


if __name__ == '__main__':
    main()

4.獲取二進位制檔案

import base64
import redis

from test1 import Student


def main():
    client = redis.StrictRedis(host='47.107.175.127',
                               password='123456')

    with open('C:\\Users\\DELL\\Desktop\\ywl.jpg', 'wb') as f:
        photo = client.get('photo')
        f.write(base64.b64decode(photo))


if __name__ == '__main__':
    main()

三、第二階段總結

1.網路應用的模式

網路應用的模式:C/S、B/S、P2P
client-server
browser-server
peer-to-peer

移動端(手機)/PC端(瀏覽器) + Web後端
HTML + CSS + JavaScript --> 前端(前端展示的資料是由後端的程式提供的)
後端 ===> 運算 + 儲存 ===> 用Python程式為前端提供資料和服務
Django + Flask


2.前端知識

1.CSS - 選擇器 / 優先順序 / 盒子模型
2.JavaScript - ES / BOM(window) / DOM(document)

document
- createElement / appendChild / insertBefore
- removeChild
- innerHTML / textContent
- getElementById / getElementsByClassName / getElementsByTagName / querySelector / querySelectorAll

Ajax - jQuery
    - $.ajax({})
    - $.getJSON(url, function() {})

3.Linux
- 常用命令(檔案操作/許可權/工具/程式/網路)
- 安裝軟體(yum / 原始碼構建安裝)
- vim使用

4.資料庫
- 關係型 - MySQL - SQL(DDL / DML / DCL)
- select - 投影/別名/篩選/模糊/排序/分組/聚合函式/分頁/子查詢/連線查詢
- NoSQL - Redis - 快取


四、通訊錄

import pymysql


class Person(object):

    def __init__(self, name, tel, sex, addr, remark):
        self.name = name
        self.tel =tel
        self.sex = sex
        self.addr = addr
        self.remark = remark

    def __str__(self):
        return f'{self.name}\t{self.tel}\t{self.sex}\t\t{self.addr}\t{self.remark}\t'


def system_page():
    print('\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
    print('+                                                               +')
    print('                          歡迎來到通訊錄                          ')
    print('+                           1. 新增                             +')
    print('+                           2. 查詢                             +')
    print('+                           3. 刪除                             +')
    print('+                           4. 修改                             +')
    print('+                           5. 退出                             +')
    print('+                                                               +')
    print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')


def add_person(cursor):
    name = input('請輸入姓名:')
    tel = input('請輸入電話號碼:')
    if len(tel) != 11:
        print('電話號碼只能是11位,請重新輸入!')
        tel = input('請輸入電話號碼:')
    sex = input('請輸入性別:')
    if sex != '男' and sex != '女':
        print('性別只能是男或女,請重新輸入!')
        sex = input('請輸入性別:')
    addr = input('請輸入聯絡地址:')
    remark = input('請輸入備註:')
    result = cursor.execute('insert into addr_book(name, tel, sex, addr, remark) values(%s,%s,%s,%s,%s)', (name, tel, sex, addr, remark))
    if result == 1:
        print('新增成功!')
    else:
        print('新增失敗!')


def query_person(cursor):
    name = input('請輸入姓名:')
    cursor.execute('select name, tel, sex, addr, remark  from addr_book where name=%s ', (name,))
    persons = cursor.fetchall()
    print('姓名\t聯絡電話\t性別\t聯絡地址\t\t備註\t')
    for person in persons:
        person = Person(**person)
        print(person)


def del_person(cursor):
    name = input('請輸入姓名:')
    result = cursor.execute('delete from addr_book where name=%s', (name,))
    if result == 1:
        print('刪除成功!')
    else:
        print('刪除失敗!')


def update_person(cursor):
    name = input('請輸入姓名:')
    tel = input('請輸入新號碼:')
    addr = input('請聯絡地址:')
    result = cursor.execute('update addr_book set tel=%s, addr=%s where name=%s', (tel, addr, name))
    if result == 1:
        print('修改成功!')
    else:
        print('修改失敗!')


def main():
    con = pymysql.connect(host='localhost',
                          port=3306,
                          user='root',
                          passwd='123456',
                          database='abs',
                          charset='utf8',
                          autocommit=True,
                          cursorclass=pymysql.cursors.DictCursor
                          )
    try:
        with con.cursor() as cursor:
            system_page()
            operate = input('請選擇操作:')
            if operate == '1':
                add_person(cursor)
            elif operate == '2':
                query_person(cursor)
            elif operate == '3':
                del_person(cursor)
            elif operate == '4':
                update_person(cursor)
            elif operate == '5':
                exit()
    except pymysql.MySQLError as e:
        print('操作失敗!', e)
    finally:
        con.close()


if __name__ == '__main__':
    main()

相關文章