I am using Flask with Flask-RESTful. I have POST method which gets data and I need to apply validation checks on it. My question is can i use Flask-WTF with that like Django-Forms for handling validations and checks?

我正在使用带有Flask-RESTful的Flask。我有POST方法获取数据,我需要对它进行验证检查。我的问题是我可以像使用Django-Forms那样使用Flask-WTF来处理验证和检查吗?

What technique do you prefer for the scenario for Signup where i need to check if an Email already exists in the system?

对于Signup的场景,您更喜欢哪种技术?我需要检查系统中是否已存在电子邮件?

1 个解决方案

#1


1

The reqparse module of Flask-RESTful provides what you are looking for. By defining your own type of input fields, you can perform some validation operations. Here is an example from scratch:

Flask-RESTful的reqparse模块提供了您正在寻找的内容。通过定义自己的输入字段类型,您可以执行一些验证操作。这是一个从头开始的例子:

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. For example, some extensions of WTForms generate forms from models similarly to how it can be done for Django ORM models.

但是,即使使用WTForms实现,除非使用兼容的ORM,否则必须定义表单的字段。例如,WTForms的一些扩展从模型生成表单,类似于如何为Django ORM模型完成。

更多相关文章

  1. Oracle表按字段和|分格符导出文件
  2. 是否遇到过MySQL workbench text字段不能直接放入json格式内容
  3. 求sql【复制同一表记录,但有两个字段需要修改--详情 Btn_oncliek
  4. 查询表中的某一行,表中没有行号相关的属性字段,SQL语句怎么写啊?50
  5. SQL根据某个字段分组查询:
  6. mysql中如何对text字段值进行追加更新
  7. 怎么用SQL语句实现表中的一个字段加1啊??
  8. MySQL实现表之间的字段更新
  9. sql2005指定字段插入空格。

随机推荐

  1. Paypal 支付功能的 C# .NET / JS 实现
  2. 区分C++常量表达式、const、constexpr(附
  3. C++学习基础知识--this指针、静态成员、
  4. C++异常处理:系统函数terminate的调用
  5. Microsoft C++ 语言扩展:try-except 语句
  6. 关于C++中string类对象的用法总结
  7. C++解决方法:多线程同步经典案例之生产者
  8. C++---浅拷贝、深拷贝、写时拷贝讲解(附代
  9. 第六章C++:函数基础与应用
  10. C#入门经典学习阶段小结(凌乱)