操作redis數(shù)據(jù)庫:
string類型
1. 增 set,傳倆個(gè)參數(shù) key value(只要是字符串就行)
2. 刪 delete 傳一個(gè)參數(shù) key
3. 修改 set 在目標(biāo)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變字符串內(nèi)置函數(shù)
s.encode() #字符串變成bytes
#刪除
r.delete('nhy_info') #刪一個(gè)不存在的key,返回0
r.flushall() #清空所有數(shù)據(jù)庫里面的數(shù)據(jù)
r.flushdb() #只清空當(dāng)前數(shù)據(jù)庫里面的數(shù)據(jù)
print(r.keys()) #獲取到所有的key
print(r.keys('*session*')) #模糊匹配含有session的關(guān)鍵詞
r.set('名稱','小明',10)#添加10,即10秒后失效
r.set('qml_session','sdfsdfsdfss')#
r.expire('qml_session',30) #追加過期時(shí)間
print(r.get('名稱')) #查key的值
# 哈希類型
r.hset('sms_code','18612532945','121213') #增加值,倆層key
r.hset('sms_code','18612532941','121313') #增加值,倆層key,第一個(gè)參數(shù)跟上邊那個(gè)一樣
print(r.hget('sms_code','18201034732')) #獲取值,要輸入倆層key
print(r.hgetall('sms_code')) #返回一個(gè)字典k=v
r.hdel('sms_code','18201034732') #刪除指定的key值
r.delete('sms_code') #把整個(gè)key刪除掉
print(r.type('sms_code')) #返回hash
print(r.type('lyl_session007'))
r.set('yulin:xxx','{"username":"yulin"}')#第一層key的值,json
牛刀小試——遷移redis
需求&思路:
1、把現(xiàn)在這個(gè)redis數(shù)據(jù)庫里面的數(shù)據(jù)全部整到另外一個(gè)redis里面
# a 有數(shù)據(jù)
# b 空
要把a(bǔ) redis里面的數(shù)據(jù) 全部到遷移到b redis
# 1、連上2個(gè)redis
# 2、先從a redis里面獲取到所有key
# 3、然后判斷key是什么類型,根據(jù)類型來判斷使用什么方法寫入
# 4、從a redis里面獲取到數(shù)據(jù),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的類型,選擇對(duì)應(yīng)的set方式
a_data = r.get(k)#從aredis獲取到的數(shù)據(jù)
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'):
#時(shí)間戳轉(zhuǎn)格式化好的時(shí)間
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'):
#格式化的時(shí)間轉(zhuǎn)時(shí)間戳
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('調(diào)用了')
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:#判斷文件的時(shí)間是否大于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__':
#判斷如果是在別的文件里面導(dǎo)入這個(gè)python文件的話,就不執(zhí)行下面的代碼
print(strTotimestamp())
print(clean_log('.'))
print(clean_log('.',2))
模塊導(dǎo)入順序:
導(dǎo)入自己寫的tools.py模塊,標(biāo)紅沒關(guān)系,其實(shí)沒有錯(cuò),是pyharm沒那么智能,識(shí)別不到而已。可以手動(dòng)加入到環(huán)境變量中,就不標(biāo)紅了
手動(dòng)加入:
手動(dòng)加入到環(huán)境變量:右擊目標(biāo)文件—mark directory as—source root,然后就可以直接用子目錄下的模塊,不需再‘文件名.然后函數(shù)名’使用
手動(dòng)加入到環(huán)境變量后,文件會(huì)變藍(lán)。而且也不變紅了。下次打開pycharm還能使用。
import 導(dǎo)入一個(gè)模塊的實(shí)質(zhì)就是把這個(gè)python文件從頭到尾執(zhí)行一次。
# 1. 直接導(dǎo)入文件名兒,里邊的函數(shù)要用 ‘文件名.函數(shù)()’
import my
print(dir(my))
print(my.sayName())
# 2. 從文件名兒里邊導(dǎo)入函數(shù),可以直接用函數(shù)
from my import sayName
print(sayName())
import 查找順序:
1. 當(dāng)前目錄
2. sys.path(python安裝的目錄)
如果當(dāng)前目錄和其他目錄有一個(gè)一樣的文件名,出來是當(dāng)前目錄的
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、復(fù)制一份
#3、在復(fù)制的excel上修改
#4、保存
book = xlrd.open_workbook('stu3.xls') #打開表格
new_book = copy.copy(book) #復(fù)制一份
sheet = new_book.get_sheet(0) #修改excel的時(shí)候,得用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() #新建一個(gè)excel
sheet = book.add_sheet('sheet1') #添加一個(gè)sheet頁
#這種方法效率不高
sheet.write(0,0,'編號(hào)') #在A1寫上‘編號(hào)’
sheet.write(0,1,'名字') #在B1寫上‘名字’
sheet.write(0,2,'性別')
sheet.write(1,0,'1')
sheet.write(1,1,'馬春波')
sheet.write(1,2,'男')
#把二維數(shù)組里的內(nèi)容寫到表格中:
stu_info = [
['編號(hào)','姓名','密碼','性別','地址'],
[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
#這樣寫稍微快一點(diǎn):
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內(nèi)置函數(shù)
for index,value in enumerate(stu_info): #同時(shí)取下標(biāo)和值
for index2,v2 in enumerate(value):
print(index,index2,v2)
sheet.write(index,index2,v2)
book.save('stu3.xls') #wps xls xlsx ,微軟的office 用 xls
接口開發(fā)
注意:添加debug=True,修改代碼后會(huì)自動(dòng)運(yùn)行,不能再點(diǎn)擊運(yùn)行了,只能刷新
可以用自己電腦的IP登錄,自己電腦還能用返回的127.0.0.1 登錄。要想別人登錄,改為host='0.0.0.0'
import flask #引入接口模塊,flask燒瓶的意思
import tools #自己寫的腳本tools里面有my_db和my_md5函數(shù)
import json
server = flask.Flask(__name__)#新建一個(gè)服務(wù),把當(dāng)前這個(gè)python文件當(dāng)做一個(gè)服務(wù)
@server.route('/login',methods=['get']) #接口路徑,請(qǐng)求方式
def hello(): #登錄函數(shù)
uname = flask.request.values.get('username')#要求傳參
pd = flask.request.values.get('passwd')
sql = 'select * from app_myuser where username="%s"'%uname #從數(shù)據(jù)庫選擇用戶名為uname的數(shù)據(jù)
res = tools.my_db(sql)
if res: #如果存在uname這個(gè)用戶,即返回了值
if tools.my_md5(pd) == res.get('passwd'): #fetchone取回一個(gè)數(shù)據(jù){‘username’:'nhy','passwd':'123456'}。字典的get方法查值,不會(huì)報(bào)錯(cuò),key不存在是返None
res = {"code":0,"msg":"登錄成功!"}
else:
res = {"code":1,"msg":"密碼錯(cuò)誤!"}
else:
res = {'code':2,"msg":"用戶不存在"}
return json.dumps(res,ensure_ascii=False,indent=4) #把字典變成json,方便儲(chǔ)存,再拿出來用方便。而且必須有返回值
@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) #運(yùn)行這個(gè)服務(wù)
#ip:8000/login
#127.0.0.1
讀取excel
import xlrd #引入表格讀模塊
book = xlrd.open_workbook('stu3.xls') #打開表格
sheet = book.sheet_by_index(0) #通過索引找到第一個(gè)表
sheet = book.sheet_by_name('sheet1') #通過名稱找到第一個(gè)表
print(sheet.cell(0,0).value) #獲取表中指定單元格A1的內(nèi)容
print(sheet.cell(1,0).value)#獲取表中指定單元格B1的內(nèi)容
print(sheet.row_values(0)) #獲取整行的數(shù)據(jù)
print(sheet.row_values(1))
print(sheet.col_values(0))#獲取整列的數(shù)據(jù)
print(sheet.col_values(1))
print(sheet.nrows) #行數(shù) number of rows
print(sheet.ncols) #列數(shù)
for row in range(1,sheet.nrows):
print(sheet.row_values(row)) #取每行的值
上周回顧:
1、內(nèi)置函數(shù)
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、函數(shù)的一點(diǎn)補(bǔ)充
遞歸:函數(shù)自己調(diào)用自己。
3、匿名函數(shù)
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
下面是電腦上裝了多個(gè)版本的python
那你要去python的安裝目錄下,分別把python.exe
改個(gè)名字,能區(qū)分出來是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數(shù)據(jù)庫操作
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:\\') #遞歸循環(huán)一個(gè)目錄
這周內(nèi)容:
1、模塊相關(guān)的,導(dǎo)入模塊流程、導(dǎo)入的模塊的實(shí)質(zhì)
1、import xx
import 一個(gè)模塊的實(shí)質(zhì)就是把這個(gè)python文件從頭到尾執(zhí)行一遍
2、import模塊的查找模塊的順序
1、從當(dāng)前目錄下找
2、sys.path
從上面2個(gè)目錄都找不到,那就報(bào)錯(cuò)
2、redis 操作、excel
redis
1.關(guān)系型數(shù)據(jù)庫
mysql、oracle、sql server
database
table1 user
table2 account
table3 order
niuhanyang
user_id
sql語句來操作數(shù)據(jù)
數(shù)據(jù)是存在磁盤上的
2.非關(guān)系型數(shù)據(jù)庫、NOSQL
1、數(shù)據(jù)是存在內(nèi)存里面
2、不需要通過sql語句來查詢數(shù)據(jù)
MongoDB
數(shù)據(jù)也是存在磁盤上的
redis
memcache
key = vaule
ip:8000/pay?xxx=xxx
3、接口開發(fā)
1、mock 服務(wù)
2、給別人提供數(shù)據(jù)
3、
flask web框架
上周作業(yè)
# 作業(yè)1
#、 寫一個(gè)函數(shù),傳入一個(gè)路徑和一個(gè)關(guān)鍵字(關(guān)鍵字是文件內(nèi)容),找到文件內(nèi)容里面有這個(gè)關(guān)鍵字的txt文件
# 1、去找到這個(gè)目錄下面的所有.txt文件
# 2、循環(huán)打開所有的txt文件,讀到文件內(nèi)容
# 3、判斷關(guān)鍵字是否存在文件里面
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('文件內(nèi)容在',abs_file_path)
#2、刪除3天前的日志文件
#1、要獲取到所有的日志文件 os.walk()
#2、先獲取到文件的時(shí)間
#3、要判斷文件的日期是否在三天前 當(dāng)天的日期的時(shí)間戳 - 60*60*24*3
import time
def timestampToStr(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
#時(shí)間戳轉(zhuǎn)格式化好的時(shí)間
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'):
#格式化的時(shí)間轉(zhuǎn)時(shí)間戳
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:#判斷文件的時(shí)間是否大于3天
os.remove(os.path.join(cur_path,file))
#clean_log(r'/Users/nhy/PycharmProjects/tcz/day6')
#find_content(r'/Users/nhy/PycharmProjects/tcz','函數(shù)')
# 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('賬號(hào)/密碼長度錯(cuò)誤,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('失敗次數(shù)過多!')
def login():
for i in range(3):
username = input('請(qǐng)輸入用戶名:').strip().upper()
password = input('請(qǐng)輸入密碼:').strip()
sql='select username,passwd from app_myuser where username = "%s";'%username
if username =='' or password =='':
print('賬號(hào)/密碼不能為空')
else:
res = my_db(sql) # {'username':nhy 'passwd':'xxxxx'}
if res:
if my_md5(password) == res.get('passwd'):
print('登陸成功!')
break
else:
print('密碼錯(cuò)誤!')
else:
print('用戶不存在')
else:
print('錯(cuò)誤次數(shù)過多!')
# login()
本周作業(yè):
1、寫一個(gè)函數(shù),實(shí)現(xiàn),傳入一個(gè)表名,把這個(gè)表里面的所有數(shù)據(jù)導(dǎo)出到excel里面
def data_to_excel(table_name):
pass
book.save(table_name.xls)
2、寫一個(gè)函數(shù),把a(bǔ)pp_myuser 這個(gè)表里面的數(shù)據(jù)全放到redis里面
key的樣式 :qml:wangcan1
redis key的類型用 string、hash都型
下面是存到redis里面的數(shù)據(jù)格式
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、改造登錄接口,用戶數(shù)據(jù)從redis里面取
4、注冊接口,注冊完之后,用戶信息寫到redis里面,要判斷用戶是否存在,密碼存密文
yulin:yulin {"id":1,"username":"wangcan1","password":"8b634156edde77e407764d5166e34d20","is_admin":1}