Created
November 18, 2018 05:01
-
-
Save hnuzhoulin/59293c7f06ad6f802cc9ac3ca3ffdb20 to your computer and use it in GitHub Desktop.
flask-restful reqparse check nested args,can archive required and allowed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#! -*- encoding:utf-8 -*- | |
# Author: Zhoulin | |
# FIle: nested_RequestParser | |
# Description: This method,the nested parser do not support required. | |
# Created: 2018/11/17 23:54 | |
# Modified: | |
# 2018/11/17 23:54 : | |
# --------------------------------- | |
import traceback | |
from datetime import datetime | |
from flask import Flask, got_request_exception | |
from flask_restful import Resource, Api, reqparse | |
from cerberus import Validator | |
app = Flask(__name__) | |
api = Api(app) | |
import json | |
def config_validator(value): | |
CONFIG_SCHEMA = { | |
'back_storage': {'required': True, "allowed":["filestore", "bluestore"]}, | |
'db_type': {'required': True, 'allowed': ["leveldb", "rocksdb"]}, | |
'message_type': {'required': True, 'allowed': ["simple", "async"]} | |
} | |
v = Validator(CONFIG_SCHEMA) | |
if v.validate(value): | |
return value | |
else: | |
raise ValueError(json.dumps(v.errors)) | |
class S3AdminAPIBase(Resource): | |
def __init__(self): | |
"""TODO: to be defined1. """ | |
self.parser = reqparse.RequestParser() | |
self.parser.add_argument('XX',required=True, | |
help='NetEase auth token required') | |
self.args = self.parser.parse_args() | |
class test(S3AdminAPIBase): | |
def post(self): | |
self.parser.add_argument('config', type=config_validator, action='update') | |
self.args = self.parser.parse_args() | |
return self.args | |
api.add_resource(test, '/test') | |
if __name__ == '__main__': | |
app.run(debug=True, host="0.0.0.0", port=5001) | |
# curl -X "POST" "http://127.0.0.1:5001/test" -H 'Content-Type: application/json; charset=utf-8' -d $'{"XX": "zlyf","config": {"db_type": "leveldb","back_storage": "filestore","message_type": "ccc"}}' | |
# { | |
# "message": { | |
# "config": "{\"message_type\": [\"unallowed value ccc\"]}" | |
# } | |
# } | |
# curl -X "POST" "http://127.0.0.1:5001/test" -H 'Content-Type: application/json; charset=utf-8' -d $'{"XX": "zlyf","config": {"db_type": "leveldb","back_storage": "filestore","message_type": "simple"}}' | |
# { | |
# "XX": "zlyf", | |
# "config": { | |
# "back_storage": "filestore", | |
# "db_type": "leveldb", | |
# "message_type": "simple" | |
# } | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment