flask_restful接口设计,postman测试

最经典的就是看原版文档:

快速入门 — Flask-RESTful 0.3.1 documentation

其实蛮简单,照猫画虎就是

class RestInterface(Resource):
    def get(self,id):
        return {id: 'hello world'}
    def put(self,id):
        cardNo=request.json['cardNo']
        cardID=request.json['cardID']
        print("request data:",cardNo,cardID)
        
        deviceID=searchhome(id)
        if deviceID==None:
            return{"ack":"no such room id"}
        if (int(cardNo)>100)|(int(cardNo)<0):
            return {"ack":"cardNo error"}
        if (len(cardID)!=10):
            return {"ack":"wrong cardID"}
        try:
            addCard(deviceID[6:16],cardNo,cardID)
            return{"ack":"OK"}
        except Exception as e: 
            return {"ack":("error:  "+str(e)) }

api.add_resource(RestInterface, '/api/')  # id is room number

测试程序设计:

HOST_DEFAULT="http://127.0.0.1:6001"# "http://203.195.224.224:6001"
from requests import put,get
import json

url=HOST_DEFAULT+"/api/5-2011"
body={"cardNo":10,"cardID":"0102030405","user":"testing","password":"testing"}
print("ready to connect:",url)
print("ready to send data: ",body)
r = put(url=url, data=body )
print("return value: ", r)
print("unformatingg: ",r.json())


测试程序通过后,发给了客户,但是用flidder或者postman一类的测试工具测试接口,总返回400错误,百思不得其解,

后面发现问题在于接口设计的这一句

cardNo=request.json['cardNo']开始用成了例子里的form,改为json后正确通过

flask_restful接口设计,postman测试_第1张图片

你可能感兴趣的:(web,python,flask,postman)