接口開發:
import flask import tools import json,redis import random server = flask.Flask(__name__) #新建一個服務,把當前這個python文件當作一個服務 ip = '118.24.3.40' password='HK139bc&*' r = redis.Redis(host=ip,password=password,port=6379,db=10, decode_responses=True)#鏈接redis #登陸接口 @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 # res = tools.my_db(sql) key='nhy:%s'%uname res = r.get(key) if res: res = json.loads(res) if tools.my_md5(pd) == res.get('passwd'): res = {"code":0,"msg":"登陸成功!"} else: res = {"code":1,"msg":"密碼錯誤!"} else: res = {'code':2,"msg":"用戶不存在"} return json.dumps(res,ensure_ascii=False,indent=4) #註冊接口 @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') key='nhy:%s'%uname res = r.get(key) if res: res = {'code': 2, "msg": "用戶已存在"} else: md5_password = tools.my_md5(pd) res = {'id':random.randint(100,9999),'username':uname,'passwd':md5_password,'is_admin':1} r.set('nhy:%s'%uname,json.dumps(res))# res = {"code":0,"msg":"註冊成功!"} return json.dumps(res,ensure_ascii=False,indent=4) #查詢信息接口 @server.route('/api/stu') def get_stu(): username = flask.request.values.get('name')#默認get不到的話,返回的值就是None age = flask.request.values.get('age') if username and age: sql = "select * from app_student where name='%s' and age='%s'" % (username, age) elif not username and age: sql = "select * from app_student where age='%s'" % age elif username and not age: sql = "select * from app_student where name='%s'" % username else: sql = "select * from app_student" res = tools.my_db2(sql) return json.dumps(res,ensure_ascii=False,indent=4) server.run(host='0.0.0.0',port=8999,debug=True) #ip:8000/login #127.0.0.1
牛刀小試:
1. 傳入一個數據庫中的表名,而後把表裏的數據導出到excel裏面
寫excel xlwt
鏈接數據庫 pymysql
思路:
一、鏈接上數據庫,寫好 sql ='select * from %s;'%table_name
二、獲取到數據 [[id name passwd is_admin] [1,nhy,xdfsdfsd,1],[2,nhy2,xdfsdfsd,1] ]
三、循環寫入excel
四、寫表頭 hhh
import pymysql,xlwt conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',db='jxz') cur = conn.cursor() table_name = input('請輸入你要導出的表名:').strip() cur.execute('select * from %s;'%table_name) res = list(cur.fetchall()) fields = [ field[0] for field in cur.description ] # cur.description獲取到表結構 res.insert(0,fields) book = xlwt.Workbook() sheet = book.add_sheet('sheet1') for index,value in enumerate(res): for index2,v2 in enumerate(value): sheet.write(index,index2,v2) book.save('%s.xls'%table_name) cur.close() conn.close()
2. 獲取到數據庫裏面的數據
{'username':'lyl','password':xxx,'id':111,'addr':'xxx'}
而後存到redis裏面
set(lyl,{'username':'lyl','password':xxx,'id':111,'addr':'xxx'})
get(key)
import pymysql,redis,json conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',db='jxz') cur = conn.cursor(pymysql.cursors.DictCursor) cur.execute('select * from app_myuser;') data = cur.fetchall() cur.close() conn.close() ip = '118.24.3.40' password='HK139bc&*' r = redis.Redis(host=ip,password=password,port=6379,db=10, decode_responses=True)#鏈接redis for d in data: # {'username':'lyl','password':xxx,'id':111,'addr':'xxx'} key = 'nhy:%s'%d.get("username") r.set(key,json.dumps(d))
fw = open('a.txt','w',encoding='utf-8')
fw.write('時代峯峻聖誕節瘋狂樓上的房間考慮到雙方就上課了的房間開連鎖店是的范德薩')
fw = open('b.txt','w',encoding='gbk')
fw.write('時代峯峻聖誕節瘋狂樓上的房間考慮到雙方就上課了的房間開連鎖店是的范德薩')
import chardet
f= open('b.txt','rb')
res = f.read()
print(chardet.detect(res))
print(res.decode('gbk'))
python utf-8 gbk GB2312字符集
1121 牛
發送郵件:須要安裝,pip install yagmail
import yagmail username='uitestp4p@163.com' password='houyafan123'#生成受權碼,qq、16三、126都是受權碼 mail_server = 'smtp.163.com' # mail_server = 'smtp.qq.com' # mail_server = 'smtp.126.com' m = yagmail.SMTP(user=username,password=password,host=mail_server) # smtp_ssl=True,若是郵箱使用了安全協議,就須要加這個 #qq郵箱就是使用了安全協議 to = ['1137944722@qq.com','wangmei416516@163.com','511402865@qq.com'] cc = ['61378317@qq.com','1196842722@qq.com','1365834704@qq.com'] m.send(to=to,cc=cc,subject='今天吃了嗎', contents='今天吃魚肉了嗎,吃飽沒', attachments=r'tools.py')
發送網絡請求:
1. 用標準庫:
from urllib.request import urlopen #python自帶的,很差用,只需瞭解。urllib能夠發送網絡請求,urlopen能夠發送接口請求 from urllib.parse import urlencode #用於post接口請求,urlencode能夠把json字符串轉化成k=v形式 #評語:這個模塊要求類型,二進制換來換去,很麻煩。 #功能:get url request url='http://127.0.0.1:8999/api/login?username=testuser1&passwd=111111' res = urlopen(url) #發送接口請求 print(res.read().decode()) #read獲取請求返回內容,但返回二進制數據,因此再decode一下。 #功能:post url request url='http://127.0.0.1:8999/api/login' data = {'username':'testuser1','passwd':'111111'} s = urlencode(data) #把字典變成k=v形式,username=testuser1,passwd=111111 #注:‘username=testuser1,passwd=111111’,是個字符串,encode()後,變爲b'username=testuser1,passwd=111111' res = urlopen(url,s.encode()) #post請求,第二個參數要求是二進制類型,因此再encode一下 print(res.read().decode())
2. pip install requestspython
import requests import random url='http://127.0.0.1:8999/api/upload' data = {'username':'testuser1','passwd':'111111'} r = requests.get(url,params=data) #發get請求 r = requests.post(url,data=data) #發post請求 data = { "session_id":"6ab8785039dcf50fb11c53acc1db7648", "name":"zhouyongbo%s"%random.randint(1,99), "phone":"111211345%02d"%random.randint(1,99), "grade":"天秤座" } r = requests.post(url,json=data) #入參是json類型的 #上傳文件的 r = requests.post(url, data={'session_id':'6ab8785039dcf50fb11c53acc1db7648'}, files={'file_name':open('account.xls','rb') } ) # 添加header requests.get(url,headers={'cookie':'pt2gguin=o0511402865; RK=JQZpwBp1by; ptcz=6c30e26a9ed6be93d3de9e4c4aca3e55650cf99fcffa64729bd1d58a5fb209d9; pgv_pvi=779236352; pgv_pvid=6970909788; qb_qua=; qb_guid=818de686e29d412fa4ee9e99905ea166; Q-H5-GUID=818de686e29d412fa4ee9e99905ea166; NetType=; pgv_si=s4499960832; FTN5K=0138ca95; pgv_info=ssid=s4269564370; luin=o0511402865; uin=o0511402865; lskey=00010000efc2701412d3429029ac9366e4ba98f0e978e0ae4a9c684101a7b22df0695f534bc242c8d4ff386d; skey=@0sHtvhTsD; ptisp=cnc; p_uin=o0511402865; pt4_token=wGU2YAaM0uu7LbcNjuDcLN-TPrEy7AZw4gcL5TEcKxw_; p_skey=1zg7yvF5wr6l43mfr-BvNHxuVDtybKpR5RbCrgC8weQ_'}) requests.get(url,cookies={'pt2ggui':'o0511402865','RK':'JQZpwBp1by'}) print(r.text) #結果返回的就是字符串 print(r.json()) #結果返回的就是字典,必須返回的是json,才能轉成字典 #下載文件 url='https://q4.qlogo.cn/g?b=qq&nk=1834364415&s=140' url='https://qiniuuwmp3.changba.com/1127063572.mp4' r = requests.get(url) #返回的就是二進制的 r.cookies #返回cookie r.status_code #返回的狀態碼200 r.content #能夠返回圖片、音樂等 f = open('sdfsdf.mp4','wb') f.write(r.content) f.close()
接口返回值處理:
寫日誌: pip install nnlog
import nnlog nnlog.Logger.words='哈哈哈哈' log = nnlog.Logger('book_server.log','warn',when='S',backCount=5) #默認debug級別,自動清理日誌,5條就刪除 # debug 打印一些調試信息,很是多 # info 打印走到哪兒了 # warning # error #這一個語句,能夠放在須要的地方,好比登陸是,將誰在登陸寫入日誌 log.debug('xxx值是什麼') log.info('調用了什麼xxx') log.warning('xx警告!') log.error('xxx出錯!')
代碼文件:
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='118.24.3.40',user='jxz',password='123456', 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 def my_db2(sql): conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456', db='jxz',port=3306,charset='utf8',autocommit=True) cur = conn.cursor(pymysql.cursors.DictCursor) cur.execute(sql) res = cur.fetchall() #{'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))
一個python項目的文件結構:
book_server/
: 項目名mysql
conf/:存放配置文件redis
data/:存放sql文件sql
lib/
: 存放項目的全部源代碼。數據庫
logs/:存放日誌文件json
uploads/:存放下載的文件flask
start.py
: 程序啓動腳本api
readme.txt
: 項目說明文件。安全