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?
What technique do you prefer for the scenario for Signup where i need to check if an Email already exists in the system?
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:
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.
You can find more information in the documentation of Flask-RESTful.
Similarly, you can do this with 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With