请求参数

参考 http://www.pythondoc.com/Flask-RESTful/reqparse.html

  1. 大致讲解一下用法。
import time
from app import db
from ..api_1_0 import api_1_0
from flask_restful import Api, Resource, reqparse
from flask import jsonify, request
from app.models.pxeinfo import PxeInfo
from app.api_1_0.api_auth import auth

api_pxe_info = Api(api_1_0)

parser = reqparse.RequestParser()


class TestApi(Resource):
    def get(self):
        return jsonify({'test_api': 'api is ok'})


class PxeInfoApi(Resource):
    # 根据GET方式传过来的sn值,查询结果
    @auth.login_required
    def get(self):
        # 注释掉之前的传参方式
        # s = request.args.get('sn')

        # 删除掉可能存在的sn参数
        parser.remove_argument(['sn'])
        # 添加新的参数规则
        parser.add_argument('sn', type=str, required=True, help="sn cannot be blank!", location='args')
        # 获取参数数值
        args = parser.parse_args()
        s = args.get('sn')
        print(s)
        try:
            pxe_info = PxeInfo.query.filter_by(sn=s).order_by(PxeInfo.id.desc()).first()
            if pxe_info is None:
                print("{} PxeInfo query: {} failure...".format(time.strftime("%Y-%m-%d %H:%M:%S"), pxe_info['sn']))
                return False
            return pxe_info.to_json()
        except:
            print("{} PxeInfo query: {} failure...".format(time.strftime("%Y-%m-%d %H:%M:%S"), pxe_info['sn']))
            return False
        finally:
            db.session.close()


api_pxe_info.add_resource(TestApi, '/test_api', endpoint='test_api')
api_pxe_info.add_resource(PxeInfoApi, '/pxeinfo', endpoint='pxeinfo')

你可能感兴趣的:(请求参数)