Day8:接口开发
一、写日志
log.debug('xxx值是什么')
log.info('调用了什么xxx')
log.warning('xxx警告!')
log.error('xxx值是什么')
import nnlog log = nnlog.Logger('book_server.log',when='D',backCount=3) #when 没分、每秒每天、产生的back..保留5天的日志
二、发送网络请求
import requests url = '127.0.0.1:8999/api/login' data = {'username':'testuser1','passwd':'111111'} r = requests.get(url,params=data) #发请求 get r = requests.post(url,data=data) #如果url和内容里都要写参数,那就要写pararms print(r.text) #结果返回的就是字符串 print(r.json())# 结果返回的就是字典,必须返回的是json,才能转成字典
三、上传文件
r = requests.post(url,data = {'session_id':'6ab8785039dcf50fb11c53acc1db7648'}), files = {'file_name':open('account.xls','rb')
四、发送邮件
import yagmail username = '1365834704@qq.com' password = 'rsbzhzrwyayoiffh' #生成授权码,qq,163,126 都是授权码,公司自己的邮箱用密码就行 mail_server = 'smtp.qq.com' m=yagmail.SMTP(user=username,password=password,host=mail_server, smtp_ssl=True) #如果邮箱使用的安全协议就需要加这个,qq邮箱就是使用了安全协议 to = '1365834704@qq.com' cc = ['1365834704@qq.com'] m .send(to = to, cc=cc,subject='今天天气怎么样',contents='今天怎么样',attachments=r'发送邮件.py')
五、接口开发之session实现
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(): sql = 'select * from app_student' res = tools.my_db2(sql) return json.dumps(res)