day10 python接口开发、mock接口、网络编程

1.falsk接口开发、连接数据库

import flask
import datetime
import json
import tools

server=flask.Flask(__name__)
#获取当前时间接口
@server.route('/time')
def get_time():
now=str(datetime.datetime.now())
return '现在的时间是:%s'%now

@server.route('/login',methods=['post','get'])

def login():
#args只能获取到url里面的参数,values都是能正常获取
# uname=flask.request.args.get('username')
# passwd=flask.request.args.get('passwd')
uname = flask.request.values.get('username')
passwd = flask.request.values.get('passwd')
if uname and passwd:
sql="select username,passwd from app_myuser where username='%s' \
and passwd='%s'"%(uname,passwd)
result=tools.my_sql(sql)
if result:
res= {"code":"0","msg":"登录成功"}
else:
res={"code":"2001","msg":"账号密码不对"}
else:
res={"error_code":3000,"msg":"必填参数未填,请查看接口文档"}
#ensure_ascii=False 显示中文
return json.dumps(res,ensure_ascii=False,indent=5)





#host='127.0.0.2'局域网设置连接的地址

#设置debug=True 加上它就不需要重新启动了
server.run(host='0.0.0.0',port=8989,debug=True)

2.接口开发接收json格式入参
需求,开发添加学生信息接口
def add_student():
params=flask.request.json
if params:
name=params.get('name')
sex = params.get('sex','男') #如果没有传默认是男
age = params.get('age') #int
addr = params.get('addr')
grade = params.get('grade')
phone = str(params.get('phone') )#电话只能是11位,校验电话是否重复
# name = params.get('name')
gold = str(params.get('gold') )#金币可以是小数
if name and age and addr and grade and phone:
if sex not in ['男',"女"]:
res={"error_code":"3002","msg":"输入的性别有误"}
elif len((phone))!=11 or not phone.isdigit():
res = {"error_code": "3002", "msg": "输入的手机号码有误"}
elif not str(age).isdigit() or int(age)<0:
res = {"error_code": "3002", "msg": "输入的年龄有误"}
elif not gold.isdigit() and not tools.check_float(gold) :
res = {"error_code": "3002", "msg": "输入的金币有误"}
else:
sql="select phone from app_student where phone='%s'"%(phone)
reuslt=tools.my_sql(sql)
if reuslt:
res={"error_code": "3004", "msg": "手机号重复"}
else:
sql="insert into app_student (NAME ,sex,age,addr,grade,phone,gold) values('%s','%s','%s','%s','%s','%s','%s')"%(name,sex,age,addr,grade,phone,gold)
tools.my_sql(sql)
res={"code":"0","msg":"添加学生信息成功"}
else:
res={"error_code":"3001","msg":"必填参数未填请查看接口文档"}

else:
res={"error_code":"3001","msg":"入参不能为空"}

3.上传文件接口




猜你喜欢

转载自www.cnblogs.com/zzzao/p/9943975.html