1. 程式人生 > >操作redis資料庫 & 操作Excel & 開發介面

操作redis資料庫 & 操作Excel & 開發介面


操作redis資料庫:

string型別

1. 增 set,傳倆個引數 key value(只要是字串就行)
2. 刪 delete 傳一個引數 key
3. 修改 set 在目標key重新傳參 key value
4. 查 get
import redis
ip = 'xxxxxx'
password='xxxxxx'
r = redis.Redis(host=ip,password=password,port=6379,db=10,
                decode_responses=True)#連線redis,加入decode_responses=True後,傳回的就不是betes型別了,而是字串。
r2 = redis.Redis(host=ip,password=password,port=6378,db=10, decode_responses=True)#連線redis
#增 set, key value
r.set('nhy_sessionn','sdfsdfssdf234sfdfsdsdfs',) 
r.set('nhy_info','{"name":"xxxx","password":"123456","account":11234}') #value只要是字串就行
#查
res = r.get('nhy_info') #返回key為nhy_info的值,是bytes型別 print('bytes..',res) print('zifuchuan..',res.decode()) #decode()是bytes變字串內建函式 s.encode() #字串變成bytes
#刪除
r.delete('nhy_info') #刪一個不存在的key,返回0
r.flushall() #清空所有資料庫裡面的資料
r.flushdb() #只清空當前資料庫裡面的資料

print(r.keys()) #獲取到所有的key
print(r.keys('*session*')) #模糊匹配含有session的關鍵詞

r.set('名稱','小明',10)#新增10,即10秒後失效

r.set('qml_session','sdfsdfsdfss')#
r.expire('qml_session',30) #追加過期時間

print(r.get('名稱')) #查key的值

# 雜湊型別
r.hset('sms_code','18612532945','121213') #增加值,倆層key
r.hset('sms_code','18612532941','121313') #增加值,倆層key,第一個引數跟上邊那個一樣

print(r.hget('sms_code','18201034732')) #獲取值,要輸入倆層key
print(r.hgetall('sms_code')) #返回一個字典k=v

r.hdel('sms_code','18201034732') #刪除指定的key值
r.delete('sms_code') #把整個key刪除掉

print(r.type('sms_code'))  #返回hash
print(r.type('lyl_session007'))

r.set('yulin:xxx','{"username":"yulin"}')#第一層key的值,json

牛刀小試——遷移redis
需求&思路:
1、把現在這個redis資料庫裡面的資料全部整到另外一個redis裡面
# a 有資料
# b 空
要把a redis裡面的資料 全部到遷移到b redis
# 1、連上2個redis
# 2、先從a redis裡面獲取到所有key
# 3、然後判斷key是什麼型別,根據型別來判斷使用什麼方法寫入
# 4、從a redis裡面獲取到資料,set 到b redis裡面
import redis
ip = '118.24.3.40'
password='HK139bc&*'
r = redis.Redis(host=ip,password=password,port=6379,db=3,
                decode_responses=True)#連線redis
r2 = redis.Redis(host=ip,password=password,port=6378,db=2,
                decode_responses=True)#連線redis
all_key = r.keys()  #從r拿到所有的key
for k in all_key: if r.type(k) == 'string': #判斷key的型別,選擇對應的set方式 a_data = r.get(k)#從aredis獲取到的資料  r2.set(k,a_data) elif r.type(k) =='hash': hash_data = r.hgetall(k) #返回字典 {'key1':'v1',key2:v2} for key,v in hash_data.items(): r2.hset(k,key,v)

tools.py檔案:
import time
import os
def timestampToStr(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    #時間戳轉格式化好的時間
    if timestamp:
        time1 = time.localtime(timestamp)
        res = time.strftime(format, time1) else: res = time.strftime(format) return res #20180304153958 def strTotimestamp(str=None,format='%Y%m%d%H%M%S'): #格式化的時間轉時間戳 if str: timep = time.strptime(str, format) res = time.mktime(timep) else: res = time.time() return int(res) def clean_log(path,day=3): print('呼叫了') for cur_path, dirs, files in os.walk(path): for file in files: if file.endswith('log'): f_time = file.split('.')[0].split('_')[-1] file_timestamp = strTotimestamp(f_time,'%Y-%m-%d') cur_timestamp = strTotimestamp(time.strftime('%Y-%m-%d'),'%Y-%m-%d') if (cur_timestamp - file_timestamp) >= 60*60*24*day:#判斷檔案的時間是否大於3天  os.remove(os.path.join(cur_path,file)) import pymysql def my_db(sql): conn = pymysql.connect(host='xxxxxx',user='xxxxxx',password='xxxxxx', db='jxz',port=3306,charset='utf8',autocommit=True) cur = conn.cursor(pymysql.cursors.DictCursor) cur.execute(sql) res = cur.fetchone() #{'username':'nhy'} {}  cur.close() conn.close() return res import hashlib def my_md5(s,salt=''): s = s+salt news = str(s).encode() m = hashlib.md5(news) return m.hexdigest() if __name__ == '__main__': #判斷如果是在別的檔案裡面匯入這個python檔案的話,就不執行下面的程式碼 print(strTotimestamp()) print(clean_log('.')) print(clean_log('.',2))

模組匯入順序:

匯入自己寫的tools.py模組,標紅沒關係,其實沒有錯,是pyharm沒那麼智慧,識別不到而已。可以手動加入到環境變數中,就不標紅了

手動加入:
手動加入到環境變數:右擊目標檔案—mark directory as—source root,然後就可以直接用子目錄下的模組,不需再‘檔名.然後函式名’使用
手動加入到環境變數後,檔案會變藍。而且也不變紅了。下次開啟pycharm還能使用。
import 匯入一個模組的實質就是把這個python檔案從頭到尾執行一次。
# 1. 直接匯入檔名兒,裡邊的函式要用 ‘檔名.函式()’
import my
print(dir(my))
print(my.sayName())

# 2. 從檔名兒裡邊匯入函式,可以直接用函式
from my import sayName
print(sayName())

import 查詢順序:

1. 當前目錄
2. sys.path(python安裝的目錄)
如果當前目錄和其他目錄有一個一樣的檔名,出來是當前目錄的
import sys
print(sys.path)
sys.path.append(r'/Users/nhy/PycharmProjects/tcz/day6')
sys.path.insert(0,r'/Users/nhy/PycharmProjects/tcz/day6')
print(sys.path)

 

修改Excel

import xlrd #引入表格讀模組

from xlutils import copy

#1、先開啟原來的excel
#2、複製一份
#3、在複製的excel上修改
#4、儲存

book = xlrd.open_workbook('stu3.xls') #開啟表格
new_book = copy.copy(book) #複製一份
sheet = new_book.get_sheet(0) #修改excel的時候,得用get_sheet()找到sheet, 不再是sheet_by_index(0)
sheet.write(0,0,'id') sheet.write(0,3,'password') new_book.save('stu3.xls')

 

寫excel

import xlwt #引入表格寫模組

book = xlwt.Workbook() #新建一個excel
sheet = book.add_sheet('sheet1') #新增一個sheet頁

#這種方法效率不高
sheet.write(0,0,'編號') #在A1寫上‘編號’
sheet.write(0,1,'名字') #在B1寫上‘名字’
sheet.write(0,2,'性別')

sheet.write(1,0,'1')
sheet.write(1,1,'馬春波')
sheet.write(1,2,'男')

#把二維數組裡的內容寫到表格中:
stu_info  = [ ['編號','姓名','密碼','性別','地址'], [1,'machunbo','sdfsd23sdfsdf2','男','北京'], [2,'machunbo2','sdfsd23sdfsdf2','男','北京'], [3,'machunb3','sdfsd23sdfsdf2','男','北京'], [4,'machunbo4','sdfsd23sdfsdf2','男','北京'], [5,'machunbo5','sdfsd23sdfsdf2','男','北京'], [6,'machunbo6','sdfsd23sdfsdf2','男','北京'], [7,'machunbo6','sdfsd23sdfsdf2','男','北京'], [8,'machunbo6','sdfsd23sdfsdf2','男','北京'], [9,'machunbo6','sdfsd23sdfsdf2','男','北京'], [10,'machunbo6','sdfsd23sdfsdf2','男','北京'], [11,'machunbo6','sdfsd23sdfsdf2','男','北京'], ] #11行5列,下邊這樣寫效率還很慢: row = 0 #第一行 for stu in stu_info: sheet.write(row,0,stu[0]) sheet.write(row,1,stu[1]) sheet.write(row,2,stu[2]) sheet.write(row,3,stu[3]) sheet.write(row,4,stu[4]) ... row+=1 #這樣寫稍微快一點: row = 0 #行 for stu in stu_info: #stu col = 0 # 列 # [1, 'machunbo', 'sdfsd23sdfsdf2', '男', '北京'], for s in stu: #控制列 sheet.write(row,col,s) #0 3 男 col+=1 row+=1 #這樣寫效率最高:引用enumerate內建函式 for index,value in enumerate(stu_info): #同時取下標和值 for index2,v2 in enumerate(value): print(index,index2,v2) sheet.write(index,index2,v2) book.save('stu3.xls') #wps xls xlsx ,微軟的office 用 xls

介面開發

注意:新增debug=True,修改程式碼後會自動執行,不能再點選運行了,只能重新整理
可以用自己電腦的IP登入,自己電腦還能用返回的127.0.0.1 登入。要想別人登入,改為host='0.0.0.0'
import flask #引入介面模組,flask燒瓶的意思
import tools #自己寫的指令碼tools裡面有my_db和my_md5函式
import json

server = flask.Flask(__name__)#新建一個服務,把當前這個python檔案當做一個服務

@server.route('/login',methods=['get']) #介面路徑,請求方式
def hello(): #登入函式
    uname = flask.request.values.get('username')#要求傳參
    pd = flask.request.values.get('passwd')
    sql = 'select * from app_myuser where username="%s"'%uname #從資料庫選擇使用者名稱為uname的資料
    res = tools.my_db(sql)
    if res: #如果存在uname這個使用者,即返回了值
        if tools.my_md5(pd) == res.get('passwd'): #fetchone取回一個數據{‘username’:'nhy','passwd':'123456'}。字典的get方法查值,不會報錯,key不存在是返None
            res = {"code":0,"msg":"登入成功!"}
        else: res = {"code":1,"msg":"密碼錯誤!"} else: res = {'code':2,"msg":"使用者不存在"} return json.dumps(res,ensure_ascii=False,indent=4) #把字典變成json,方便儲存,再拿出來用方便。而且必須有返回值  @server.route('/reg',methods=['post']) #登入程式碼 def reg(): uname = flask.request.values.get('username') pd = flask.request.values.get('passwd') cpd = flask.request.values.get('cpwd') server.run(host='0.0.0.0',port=8999,debug=True) #執行這個服務 #ip:8000/login #127.0.0.1 


讀取excel

import xlrd #引入表格讀模組
book = xlrd.open_workbook('stu3.xls') #開啟表格
sheet = book.sheet_by_index(0) #通過索引找到第一個表
sheet = book.sheet_by_name('sheet1') #通過名稱找到第一個表

print(sheet.cell(0,0).value) #獲取表中指定單元格A1的內容
print(sheet.cell(1,0).value)#獲取表中指定單元格B1的內容
print(sheet.row_values(0)) #獲取整行的資料
print(sheet.row_values(1))
print(sheet.col_values(0))#獲取整列的資料
print(sheet.col_values(1))

print(sheet.nrows) #行數 number of rows
print(sheet.ncols) #列數

for row in range(1,sheet.nrows):
print(sheet.row_values(row)) #取每行的值

上週回顧:

    1、內建函式
len
type
max()
sum()
round(5.3212,2)
char() #
ord() #
sorted()
reversed()
res = list(filter(func,[1,2,3,4,5]))
res = list(map(func,[1,2,3,4,5]))
id()
eval('1+1')

'''
import os
os.system('xxx')
'''
exec('')

2、函式的一點補充
遞迴:函式自己呼叫自己。

3、匿名函式
lambda s:str(s).isdigit()

def func(s):
return str(s).isdigit()

4、第三方模組安裝
pip install xxx
easy_install xxx 需要安裝setuptools模組
1、python操作xxx的模組
.whl
pip install pymysql.whl
.tar.gz
解壓
python3 setup.py install
下面是電腦上裝了多個版本的python
那你要去python的安裝目錄下,分別把python.exe
改個名字,能區分出來是python2還是python3
python2 -m pip install xxx
python3 -m pip install xxx

5、hashlib模組
import hashlib
s = 'xxxxx'
s = s.encode()
m = hashlib.md5(s)
res = m.hexdigest()

6、mysql資料庫操作
import pymysql
conn = pymysql.connect(host,user,db,password,port,charset,
autocommit=True)
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
'select * from user;'
cur.fetchall() # ((1,name,password),(2,name,passwd2))
cur.fetchone() # (1,name,passwrd) {'id':1,"name":name,

"password":123234}
cur.close()
conn.close()


os.walk(r'e:\\') #遞迴迴圈一個目錄

這周內容:

1、模組相關的,匯入模組流程、匯入的模組的實質
1、import xx
import 一個模組的實質就是把這個python檔案從頭到尾執行一遍
2、import模組的查詢模組的順序
1、從當前目錄下找
2、sys.path
從上面2個目錄都找不到,那就報錯

2、redis 操作、excel
redis
1.關係型資料庫
mysql、oracle、sql server
database
table1 user
table2 account
table3 order
niuhanyang
user_id
sql語句來操作資料
資料是存在磁碟上的

2.非關係型資料庫、NOSQL
1、資料是存在記憶體裡面
2、不需要通過sql語句來查詢資料
MongoDB
資料也是存在磁碟上的
redis
memcache

key = vaule

ip:8000/pay?xxx=xxx
3、介面開發
1、mock 服務
2、給別人提供資料
3、

flask web框架

上週作業
# 作業1
#、 寫一個函式,傳入一個路徑和一個關鍵字(關鍵字是檔案內容),找到檔案內容裡面有這個關鍵字的txt檔案
# 1、去找到這個目錄下面的所有.txt檔案
# 2、迴圈開啟所有的txt檔案,讀到檔案內容
# 3、判斷關鍵字是否存在檔案裡面
import os

def find_content(path,key_word):
for cur_path,dirs,files in os.walk(path):
for file in files:
if file.endswith('log'):
print(file)
abs_file_path = os.path.join(cur_path,file)
res = open(abs_file_path,encoding='utf-8').read()
if key_word in res:
print('檔案內容在',abs_file_path)


#2、刪除3天前的日誌檔案
#1、要獲取到所有的日誌檔案 os.walk()
#2、先獲取到檔案的時間
#3、要判斷檔案的日期是否在三天前 當天的日期的時間戳 - 60*60*24*3
import time
def timestampToStr(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
#時間戳轉格式化好的時間
if timestamp:
time1 = time.localtime(timestamp)
res = time.strftime(format, time1)
else:
res = time.strftime(format)
return res
#20180304153958
def strTotimestamp(str=None,format='%Y%m%d%H%M%S'):
#格式化的時間轉時間戳
if str:
timep = time.strptime(str, format)
res = time.mktime(timep)
else:
res = time.time()
return int(res)

def clean_log(path,day=3):
for cur_path, dirs, files in os.walk(path):
for file in files:
if file.endswith('log'):
f_time = file.split('.')[0].split('_')[-1]
file_timestamp = strTotimestamp(f_time,'%Y-%m-%d')
cur_timestamp = strTotimestamp(time.strftime('%Y-%m-%d'),'%Y-%m-%d')
if (cur_timestamp - file_timestamp) >= 60*60*24*day:#判斷檔案的時間是否大於3天
os.remove(os.path.join(cur_path,file))
#clean_log(r'/Users/nhy/PycharmProjects/tcz/day6')
#find_content(r'/Users/nhy/PycharmProjects/tcz','函式')
# print(os.listdir('/Users/nhy'))


#登入、註冊

import pymysql
def my_db(sql):
conn = pymysql.connect(host='xxxxxx',user='xxxxxx',password='xxxxxx',
db='jxz',port=3306,charset='utf8',autocommit=True)
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
res = cur.fetchone() #{'username':'nhy'} {}
cur.close()
conn.close()
return res
import hashlib
def my_md5(s,salt=''):
s = s+salt
news = str(s).encode()
m = hashlib.md5(news)
return m.hexdigest()

def reg():
for i in range(3):
user =input('username:').strip().upper()
pd = input('password:').strip()
cpd = input('cpwd:').strip()
sql='select username from app_myuser where username = "%s";'%user
if len(user) not in range(6,11) or len(pd) not in range(6,11): # 6 7 8 9 10
print('賬號/密碼長度錯誤,6-10位之間')
elif pd != cpd:
print('兩次輸入密碼不一致')
elif my_db(sql):
print('使用者已存在')
else:
md5_passwd = my_md5(pd)
insert_sql= 'insert into app_myuser (username,passwd,is_admin) value ("%s","%s",1);'%(
user,md5_passwd
)
my_db(insert_sql)
print('註冊成功!')
break
else:
print('失敗次數過多!')



def login():
for i in range(3):
username = input('請輸入使用者名稱:').strip().upper()
password = input('請輸入密碼:').strip()
sql='select username,passwd from app_myuser where username = "%s";'%username
if username =='' or password =='':
print('賬號/密碼不能為空')
else:
res = my_db(sql) # {'username':nhy 'passwd':'xxxxx'}
if res:
if my_md5(password) == res.get('passwd'):
print('登陸成功!')
break
else:
print('密碼錯誤!')
else:
print('使用者不存在')

else:
print('錯誤次數過多!')
# login()
本週作業:
1、寫一個函式,實現,傳入一個表名,把這個表裡面的所有資料匯出到excel裡面
def data_to_excel(table_name):
pass
book.save(table_name.xls)
2、寫一個函式,把app_myuser 這個表裡面的資料全放到redis裡面
key的樣式 :qml:wangcan1
redis key的型別用 string、hash都型
下面是存到redis裡面的資料格式
wangcan1 {"id":1,"username":"wangcan1","password":"8b634156edde77e407764d5166e34d20","is_admin":1}
wangcan2 {"id":1,"username":"wangcan1","password":"8b634156edde77e407764d5166e34d20","is_admin":1}
wangcan3 {"id":2,"username":"wangcan1","password":"8b634156edde77e407764d5166e34d20","is_admin":1}


3、改造登入介面,使用者資料從redis裡面取

4、註冊介面,註冊完之後,使用者資訊寫到redis裡面,要判斷使用者是否存在,密碼存密文
yulin:yulin {"id":1,"username":"wangcan1","password":"8b634156edde77e407764d5166e34d20","is_admin":1}