简体   繁体   English

Flask-RESTful与Flask-WTF表单集成

[英]Flask-RESTful with Flask-WTF forms integration

I am using Flask with Flask-RESTful . 我正在将FlaskFlask-RESTful I have POST method which gets data and I need to apply validation checks on it. 我有获取数据的POST方法,我需要对其进行验证检查。 My question is can i use Flask-WTF with that like Django-Forms for handling validations and checks? 我的问题是我可以将Flask-WTFDjango-Forms来处理验证和检查吗?

What technique do you prefer for the scenario for Signup where i need to check if an Email already exists in the system? 对于我需要检查系统中是否已存在电子邮件的“ Signup ”方案,您喜欢哪种技术?

The reqparse module of Flask-RESTful provides what you are looking for. Flask-RESTful的reqparse模块提供了您正在寻找的东西。 By defining your own type of input fields, you can perform some validation operations. 通过定义自己的输入字段类型,您可以执行一些验证操作。 Here is an example from scratch: 这是一个从头开始的示例:

from flask import Flask
from flask.ext.restful import Api, Resource, reqparse

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


def is_email_valid(address):
    # Check if the e-mail address already exists in database.
    return True  # or False

def email(value):
    if not is_email_valid(value):
        raise ValueError("The e-mail address {} is already taken.".format(value))

    return value

class Users(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('email', type=email, help='Signup email')

    def post(self):
        args = self.parser.parse_args()
        # Create the new user with args.items()
        return "user representation", 201


api.add_resource(Users, '/users')


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

If an argument fails to pass validation, the parser automatically responds with a 400 Bad Request. 如果参数未能通过验证,则解析器将自动以400 Bad Request进行响应。

You can find more information in the documentation of Flask-RESTful. 您可以在Flask-RESTful 文档中找到更多信息。

Similarly, you can do this with WTForms : 同样,您可以使用WTForms执行此操作:

from flask import Flask, request
from flask.ext.restful import Api, Resource, abort
from wtforms import Form, fields, validators

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


# WTForms
def is_email_valid(address):
    # Check if the e-mail address already exists in database.
    return True  # or False

def user_email(form, field):
    if not is_email_valid(field.data):
        raise validators.ValidationError("The e-mail address {} is already taken.".format(field.data))

class UserForm(Form):
    email = fields.StringField('Email', [validators.Email(), user_email])


# Flask-RESTful
class Users(Resource):
    def post(self):
        form = UserForm(data=request.get_json())
        if form.validate():
            # Create the new user with form.populate_obj()
            pass
        else:
            abort(400)
        return "user representation", 201


api.add_resource(Users, '/users')


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

However, even with the WTForms implementation, you have to define your form's fields unless you use a compatible ORM. 但是,即使使用WTForms实现,也必须定义表单的字段,除非您使用兼容的ORM。 For example, some extensions of WTForms generate forms from models similarly to how it can be done for Django ORM models. 例如,WTForms的某些扩展从模型生成表单,类似于可以为Django ORM模型完成表单的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM