Python自動化學習筆記(七)接口開發部分的內容補充python
flask.request.is_json #判斷參數是不是json格式redis
flask.request.json.get('key') #獲取參數sql
flask.request.data.get('key') #獲取參數json
file=flask.request.files.get('file_name') #獲取上傳的文件,filename爲參數名稱flask
file.save(path) #保存文件到指定目錄api
import json import time from . import tools import flask from . import check_session from conf import setting from conf.setting import log import os server=flask.Flask(__name__) @server.route('/api/login',methods=['get','post']) def login(): uname = flask.request.values.get('username') pd = flask.request.values.get('passwd') sql = 'select * from app_myuser where username="%s"' % uname log.debug('登陸執行的sql是:%s'%sql) res = tools.my_db(sql) if res: if tools.my_md5(pd) == res.get('passwd'): uname_md5 = tools.my_md5(uname + str(time.time())) # uname_md5 = tools.my_md5(uname) key = 'session:%s' % (uname_md5) user_info = {'user_id': res.get('id'), 'user_name': uname} r = tools.get_redis() log.debug('鏈接redis成功' ) log.info('用戶:%s登陸成功' % uname) r.set(key, json.dumps(user_info), setting.SESSION_EXPIRE) res = {"code": 0, "msg": "登陸成功!", 'session_id': uname_md5, 'login_time': time.strftime('%Y-%m-%d %H:%M:%S')} else: res = {"code": 1, "msg": "密碼錯誤!"} else: log.warning('用戶:%s不存在' %uname) res = {'code': 2, "msg": "用戶不存在"} return json.dumps(res, ensure_ascii=False,indent=4) @server.route('/api/add_stu',methods=['get','post']) def add_stu(): if flask.request.is_json: session_id = flask.request.json.get('session_id') stu_name = flask.request.json.get('stu_name') phone = flask.request.json.get('phone') grade = flask.request.json.get('grade') sex = flask.request.json.get('sex','男') age=flask.request.json.get('age',18) gold=flask.request.json.get('gold',1000) addr = flask.request.json.get('addr','北京') if session_id and stu_name and phone and grade: session_tag,data=check_session.check_session(session_id) if session_tag: sql = "insert into app_student (name,phone,grade,sex,age,gold,addr)VALUES ('{}','{}','{}','{}','{}','{}','{}')".format(stu_name,phone,grade,sex,age,gold,addr) tools.my_db(sql) res = {"code": 0, "msg": "學生信息添加成功!"} else: res=data else: res={'code':3,'msg':'必填參數未填,請查看接口文檔!'} else: res={'code':5,'msg':'入參必須是json類型的'} return json.dumps(res, ensure_ascii=False,indent=4) @server.route('/api/upload',methods=['get','post']) def upload(): session_id=flask.request.values.get('session_id') file=flask.request.files.get('file_name') if session_id and file: login_tag,data=check_session.check_session(session_id) if login_tag: new_file_name = '%s_%s'%(int(time.time()),file.filename) file.save(os.path.join(setting.UPLOAD_DIR,new_file_name))#保存文件 res = {"code": 0, "msg": "上傳文件成功"} else: res=data else: res = {'code': 3, 'msg': '必填參數未填,請查看接口文檔!'} return json.dumps(res, ensure_ascii=False,indent=4)
book_server/
: 項目名安全
conf/:存放配置文件服務器
data/:存放sql文件cookie
lib/
: 存放項目的全部源代碼。網絡
logs/:存放日誌文件
uploads/:存放下載的文件
start.py
: 程序啓動腳本
readme.txt
: 項目說明文件。
import requests #發送get請求 url='http://127.0.0.1:1234/api/login' data={'username':'lyc1','passwd':'111111'} # r=requests.request(method='get',url=url,data=data) r=requests.get(url,params=data) #get請求用params,請求時會把它拼接到url後面 print(r.text)#返回字符串 # print(r.json())#返回的是字典,接口返回的是json格式才能夠轉成字典 #發送post請求 url='http://127.0.0.1:1234/api/add_stu' data={ "session_id":"6ab8785039dcf50fb11c53acc1db7648", "stu_name":"測試一下", "phone":"13111111111", "grade":"天秤座", "sex":"女", "addr":"成都" } r=requests.post(url,json=data) #發送post請求,入參是json類型 print(r.text) #上傳下載文件,添加header url='http://127.0.0.1:1234/api/upload' data={'session_id':'6ab8785039dcf50fb11c53acc1db7648'} files={'file_name':open(r'E:\lyc_study\python\day8\book_server\uploads\1545551778_《天才在左瘋子在右》 (1).txt','rb')} r=requests.post(url,data=data,files=files) #發送post請求,入參是json類型 print(r.text) #添加header requests.get(url,params=data,headers={'cookie':'xxx','content':'xxxx'}) #下載文件,拿到r.content,寫入一個文件 url='https://q4.qlogo.cn/g?b=qq&nk=564428155&s=140' r=requests.get(url) with open('a.jpg','wb')as f: f.write(r.content) r.cookies #請求返回的cookie r.status_code #狀態碼
yagmail不能直接pip install yagmail,安裝的有bug,附件名稱爲中文時會亂碼
import yagmail username='xxx@qq.com' password='xxxxxxxx' #有的郵箱不能直接用密碼,須要一個客戶端受權碼,在郵件設置裏通常能夠拿到 mail_server='smtp.qq.com' #郵箱服務器 m=yagmail.SMTP(user=username,password=password,host=mail_server,smtp_ssl=True) #smtp_ssl=False,若是郵箱使用了安全協議,就必須加,QQ郵箱要加 to=['xxx@163.com','xxx@qq.com'] cc='xx@qq.com' #to爲收件人list,cc爲抄送人list,attachments爲附件list,均可以只傳入一個字符串 m.send(to=to,cc=cc,subject='吃飯沒',contents='吃了啥',attachments=r'E:\lyc_study\python\day8\book_server\uploads\1545551790_Desert.jpg')
nnlog模塊灰常好用,強烈安利
import nnlog log=nnlog.Logger('book_server.log',when='S',backCount=5) #實例化一個log對象,其餘Python文件要使用能夠直接import這個對象 #backCount指保留幾個日誌 #when='S',按秒劃分文件,m按分鐘,D按天 log.debug('寫一條dubug日誌') log.info('寫一條info錯誤') log.warning('寫一條warning日誌') log.error('寫一條error日誌')