Flask JSON验证WTForms

时间:2016-01-26 19:19:08

标签: python json flask flask-wtforms flask-restful

我正在尝试使用针对Restful API的JSONSchema验证启用flask_inputs。 代码如下所示:

from flask_inputs import Inputs
from flask_inputs.validators import JsonSchema

def GetValidSchema():
schema = {
    'type': 'object',
    'properties': {
        'name': {'type': 'string'}
    }
}
return schema


    class ApiResource(resource)

        class ApiInputs(Inputs):
            schema = InputsValidation.GetValidSchema() # this returns the JSON schema object 
            json = [JsonSchema(schema=schema)]

        def post(self):
            inputs =self.ApiInputs(request)
            print inputs.validate()


api.add_resource(ApiResource,'/test')

我真的需要一些帮助,因为我试图找出WT-Forms但不幸的是我无法得出一个明确的结论,为什么我收到以下错误:

  File "/home/seelview/run.py", line 153, in post
    inputs.validate()
      File "/usr/lib/python2.7/site-packages/flask_inputs/inputs.py", line 76, in validate
    if not form.validate():
  File "/usr/lib/python2.7/site-packages/wtforms/form.py", line 152, in validate
    if not field.validate(self, extra):
  File "/usr/lib/python2.7/site-packages/wtforms/fields/core.py", line 204, in validate
    stop_validation = self._run_validation_chain(form, chain)
  File "/usr/lib/python2.7/site-packages/wtforms/fields/core.py", line 225, in _run_validation_chain
    validator(form, self)
TypeError: 'str' object is not callable

知道我做错了什么或我错过了什么?

1 个答案:

答案 0 :(得分:0)

您正在使用验证程序之外的其他内容来污染ApiInputs命名空间。试试这个:

class ApiInputs(Inputs):
    json = [JsonSchema(schema=GetValidSchema())]

示例程序:

from flask import Flask, request
from flask_restful import Resource, Api
from flask_inputs import Inputs
from flask_inputs.validators import JsonSchema

app = Flask(__name__)
api = Api(app)


def GetValidSchema():
    return {
        'type': 'object',
        'properties': {
            'name': {'type': 'string'}}}


@app.route('/')
def clickme():
    return '''
        <form action="/test" method="POST">
        <input type=submit value="Click Me" />
        </form>'''


class ApiResource(Resource):
    class ApiInputs(Inputs):
        json = [JsonSchema(schema=GetValidSchema())]

    def post(self):
        inputs = self.ApiInputs(request)
        print inputs.validate()


api.add_resource(ApiResource, '/test')

if __name__ == '__main__':
    app.run(debug=True)