1. 程式人生 > >PYTHON自動化Day7-補充資料庫,操作excel,redis操作 ,介面開發

PYTHON自動化Day7-補充資料庫,操作excel,redis操作 ,介面開發

補充資料庫方法:

import pymysql

def mysql(sql):
    conn = pymysql.connect(
        host='118.24.3.40', user='jxz', passwd='123456',
        port=3306, db='jxz', charset='utf8'
    )
    # cur = conn.cursor()  #建立遊標
    cur=conn.cursor(cursor=pymysql.cursors.DictCursor)  #指定cur型別,返回字典
    cur.execute(sql)
    
if sql.strip()[:6].upper()=='SELECT': # print(cur.description) #獲取表頭資訊 res='' # res = cur.fetchall() #得到所有結果 # res=cur.fetchone() #得到一條結果 # res2 = cur.fetchone() # res3 = cur.fetchone() # fileds=[] # for filed in cur.description: #
fileds.append(filed[0]) fileds=[filed[0] for filed in cur.description] #列表生成式 和上面三行作用相同, 獲取表頭中的列名 print(fileds) else: conn.commit() res=1 cur.close() # 關閉遊標 conn.close() # 關閉連線 return res sql = 'select * from stu;' #寫sql語句時需要使用佔位符,不能直接在sql語句裡面寫變數名
res=mysql(sql) print(res)

一.寫excel:

import xlwt
book = xlwt.Workbook()              #新建一個excel
sheet = book.add_sheet('sheet1')    #加sheet頁
sheet.write(0,0,'姓名')              #行、列、寫入的內容
sheet.write(0,1,'年齡')
sheet.write(0,2,'性別')

book.save('stu.xls')                #必須以.xls結尾

二.通用從資料庫取資料匯出到excel:

import pymysql,xlwt
def export_excel(table_name):
    host, user, passwd, db = '118.24.3.40', 'jxz', '123456', 'jxz'
    coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8')
    cur = coon.cursor()  # 建立遊標,指定cursor型別返回的是字典
    sql = 'select * from %s ;'%table_name
    cur.execute(sql)  # 執行sql
    fileds = [filed[0] for filed in cur.description]  #所有的欄位
    all_data = cur.fetchall()
    book = xlwt.Workbook()
    sheet  = book.add_sheet('sheet1')
    for col,filed in enumerate(fileds):   #寫表頭的   enumerate 分別取出每個元素的位置和value
        sheet.write(0,col,filed)
    row = 1  #行數
    for data in all_data:  #
        for col, filed in enumerate(data):  # 控制列
            sheet.write(row, col, filed)
        row+=1#每次寫完一行,行就加1
    book.save('%s.xls'%table_name)
export_excel('app_student')

三.讀excel:

import xlrd
book = xlrd.open_workbook('app_student.xls')
sheet = book.sheet_by_index(0) #獲取到第幾個sheet頁
sheet2 = book.sheet_by_name('shee1')  #根據名字獲取到sheet頁
print(sheet.cell(0,0))  #指定sheet頁裡面行和列獲取資料 ,會包含type
print(sheet.cell(0,0).value) #指定sheet頁裡面行和lie獲取資料,只有資料,沒有type
print(sheet.cell(1,0).value) #指定sheet頁裡面行和lie獲取資料
print(sheet.row_values(0)) #這個獲取到第幾行的內容
print(sheet.row_values(1)) #這個獲取到第幾行的內容
print(sheet.nrows) #獲取到excel裡面總共有多少行
for i in range(sheet.nrows):  #迴圈獲取到每行資料
    print(sheet.row_values(i))
print(sheet.ncols)  #總共多少列
print(sheet.col_values(0)) #取第幾列的資料

四.修改excel:

import xlrd
from xlutils import copy
book = xlrd.open_workbook('stu.xls')
#先用xlrd模組,開啟一個excel
new_book = copy.copy(book)
#通過xlutils這個模組裡面copy方法,複製一份excel
sheet = new_book.get_sheet(0) #獲取sheet頁
lis = ['編號','名字','性別','年齡','地址','班級','手機號','金幣']
for col,filed in enumerate(lis):
    sheet.write(0,col,filed)

new_book.save('app_student.xls')

五.redis操作:

import redis

r = redis.Redis(host='118.24.3.40',password='HK139bc&*',db=6,port=6379)

#增刪改查
r.set('niuhanyang','帥!') #資料庫裡面新增一個值
# 修改也是set
r.delete('niuhanyang')
r.setex('python_123','哈哈哈',20)  #設定key的失效時間,最後這個引數是秒
hwt = r.get('hwt')
print(hwt.decode())
print(r.keys('*xxx*'))#獲取到所有的key
print(r.get('sdfsdf'))
r.set('天蠍座:mpp','呵呵呵')
r.get('天蠍座:mpp')

# 上面操作都是針對 string型別
for k in r.keys():  #刪除所有的key
    r.delete(k)

# 雜湊型別  hash   巢狀字典
r.hset('stu_info','劉偉','1m8 100w存款')
r.hset('stu_info','張流量','浪,為了不交作業,故意讓狗咬他')
r.hset('stu_info','董春光','為了不交作業,找了一條狗咬張流量,然後陪張流量去醫院')
print(r.hget('stu_info','張流量').decode())  #指定大key和小key獲取對應的資料
print(r.hgetall('stu_info'))  #獲取裡面所有的k和-v
stu_info  = r.hgetall('stu_info')
r.hdel('stu_info','gyx')  #刪除指定key
r.delete('stu_info')  #刪除整個key
r.expire('aaa',100) #第一個key設定失效時間
new_stu_info = {}
for k,v in stu_info.items():
    new_stu_info[k.decode()] = v.decode()
print(new_stu_info)

print(r.type('stu_info'))  #檢視key是什麼型別的
print(r.type('zll'))


s='呵呵'
s.encode() #把字串轉成二進位制
hwt = b'sdfsdfsdf'
hwt.decode()  #把bytes型別轉成字串

#pymysql、json、redis
#1、連資料庫,查到資料庫裡面所有的資料,遊標型別要用pymysql.curosrs.DictCour
#2、查到所有資料   [ {"id":1,"passwd":"49487dd4f94008a6110275e48ad09448","username":"niuhayang","is_admin":1}]
#3、迴圈這個list,取到usernamer,把username當做key
#4、再把這個小字典轉成json,存進去就ok。
import pymysql,json,redis
r = redis.Redis(host='118.24.3.40',password='HK139bc&*',db=1,port=6379)
conn = pymysql.connect(host='118.24.3.40',user='jxz',passwd='123456',db='jxz',charset='utf8')
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute('select * from my_user;')
all_data = cur.fetchall()
for data in all_data:
    k = data.get('username')
    r.hset('stu_info_nhy',k,json.dumps(data))
cur.close()
conn.close()

六.介面開發:

import flask,json
import pymysql
# __name__,代表當前這個python檔案
server=flask.Flask(__name__)  #把當前這個python檔案,當做一個服務

def mysql(sql):
    conn = pymysql.connect(
        host='118.24.3.40', user='jxz', passwd='123456',
        port=3306, db='jxz', charset='utf8'
    )
    # cur = conn.cursor()  #建立遊標
    cur=conn.cursor(cursor=pymysql.cursors.DictCursor)  #指定cur型別,返回字典
    cur.execute(sql)
    if sql.strip()[:6].upper()=='SELECT':
        res = cur.fetchall()  #得到所有結果
    else:
        conn.commit()
        res=1
    cur.close()  # 關閉遊標
    conn.close()  # 關閉連線
    return res


#ip:8000/index?uge
@server.route('/index',methods=['get'])   #@server.route 裝置器 生成一個介面, methods=['get','post']  可以寫多個,支援多個請求,如果不寫,預設是get請求,介面返回的都是json格式
def index():
    res={'msg':'這是我開發的第一個介面','msg_code':0}
    return json.dumps(res,ensure_ascii=False)  #返回json串,ensure_ascii=False新增後,可以顯示為中文  dumps和dump區別,dump是操作檔案的,

server.run(port=7777,debug=True)  #啟動介面服務  debug=True,改了程式碼之後,不用重啟就會生效,[如果直接執行,會再開啟一個服務,所以注意一定要stop掉一個之後再執行指令碼]

@server.route('/reg',methods=['post'])
def reg():
    username=flask.request.values.get('username')  #flask.request 所有使用者輸入過來的資訊, values.get獲取資訊
    pwd=flask.request.values.get('passwd')
    if username and pwd:
        sql='select *from my_user where username="%s";' %username
        if mysql(sql):
            res={'msg':'使用者名稱已存在','msg_code':2001}
        else:
            insert_sql='insert into my_user (username,passwd,is_admin) values ("%s","%s",0);' %(username,pwd)
            mysql(insert_sql)
            res={'msg':'註冊成功','msg_code':0}
    else:
        res={'msg':'必填欄位未填','msg_code':1001}

    return json.dumps(res,ensure_ascii=False)
server.run(port=7778,debug=True,host='0.0.0.0')  #指定了host,其他人也可以通過ip地址訪問了,改動需要重啟

七.自己開發一個api:

。。。

筆記:

os.walk()  #列出路徑下所有檔案
os.listdir()  #只能列出路徑下的一層檔案和資料夾
os.system('ifconfig')  #只執行命令
os.popen() # 執行命令,並獲取到結果
os.popen('ifconfig').read()  #得到執行結果

md5
hashlib
md=hashlib.md5()  #例項化
md.update(s.encode())
md.hexdigest() #得到加密結果


pymysql,pyoracle
conn=pymysql.connect(host,pwd,port,db,charset='utf8')
cur=conn.cur()
cur.execute(sql)
conn.commit()
cur.fectall() #取結果
cur.close() conn.close() excel xlwt xls=xlwt.Workbook() sheet=xls.add_sheet('sheet') sheet.write(0,0,'id') xls.save('stu.xls') 今天: 1.補充操作資料庫 fetchall() #獲取到這個sql的全部執行結果 fetchone() #獲取到這個sql的一條結果  如果sql語句的執行結果是多條資料的時候,就用fetchall 如果你能確定sql執行的結果只有一條,就用fetchone 還有一個fetchmany() #傳入一個數,返回多少條資料  cur=conn.cursor(cursor=pymysql.cursors.DictCursor) #指定遊標型別,返回字典型別  enumerate([list,list2]) #迴圈的時候,直接取到下標 2、操作redis redis也是一個數據庫。 關係型資料庫 mysql、oracle、sql server、db2、sqlite sql 資料存在磁碟上 非關係型資料庫 沒有 sql get('k') set('xx') mongodb、redis redis資料全部都是存在記憶體裡面。速度快,但是,重啟就不見了,要實現redis資料持久化,重啟前把資料儲存到磁碟上,重啟後再恢復 redis本身效能是非常好的,每秒支援30w次的讀寫。 牛牛的redis:118.24.3.40 6379 HK139bc&* 3.開發介面
    1.mock介面,在需要其他介面返回資料時,介面還沒有開發好,可以先寫一個mock模擬介面來返回值用於當前介面測試
flask是一個輕量級的介面開發框架
    4.異常處理 作業: 1、修改excel,把app_student.xls裡面的資料, 1、如果這一行資料裡面有亂碼,那麼就給他刪掉 2、再加上一列,是否畢業 3、如果班級是天蠍座的話,畢業這一列寫成畢業 4、其他班級的寫成未畢業 2、 1、改寫註冊介面的: 1、改寫我的註冊介面,讓它的密碼存成密文的。 2、資料不再存在mysql裡面,存到redis裡面,redis的key就用string型別 3、niuhanyang 7869d295e566295b51eec5d6bed67c14 4、校驗使用者是否存在 user:niuhanyang 2、參照介面文件上 http://doc.nnzhp.cn/index.php?s=/6&page_id=12 登入介面 登入成功之後,返回seesionid,使用者登入時間 sessionid 使用者名稱+當前的時間戳 md5,seesion失效時間是60分鐘 sessionid:niuhanyang {"seessionid":a5dfcb047721e02a6f8bff779c815165,"login_time":201805051820} 如果這個使用者已經登入過了,那麼就返回他的seesionid,登入時間 給多個變數賦值: host,user,passwd,db='192.22.2.2','jxm','234567','dvd'