day10 python介面開發、mock介面、網路程式設計
阿新 • • 發佈:2018-11-12
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.上傳檔案介面