Using flask wtforms validators without using a form

2024/10/9 10:26:34

I'm receiving user registration data from an iOS application and I'd like to use the validators that come with wtforms to make sure the email and password are acceptable. However, I'm not using a flask form since users are inputting the data from iOS textfields. Is it possible to check the incoming JSON data with the wtforms validators?

@auth.route('/register', methods=['POST'])
def register():try:user = User.register_fromJSON(request.json)email_success = validate_email(user)username_success = validate_username(user)if email_success == 1 and username_success == 1:db.session.add(user)db.session.commit()return jsonify({'Success': 1})else:return jsonify({'Failure': 0})except Exception:return jsonify({'Failure': 0})def validate_email(user):if User.query.filter_by(email=user.email).first() == None:return 1else:return 0def validate_username(user):if User.query.filter_by(username=user.username).first() == None:return 1else:return 0

EDIT

I created a Registration form:

class RegistrationForm(Form):email = StringField('Email', validators=[Required(), Length(1,64), Email()])username = StringField('Username', validators=[Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, 'numbers, dots or underscores')])password = PasswordField('Password', validators=[Required()])def validate_email(self, field):if User.query.filter_by(email=field.data).first():print("Email already registered.")raise ValidationError('Email already registered.')def validate_username(self, field):if User.query.filter_by(username=field.data).first():print("Username already in use.")raise ValidationError('Username already in use.')

registration function has been updated to:

@auth.route('/register', methods=['POST'])
def register():try:data = MultiDict(mapping=request.json)form = RegistrationForm(data)if form.validate():user = User.register_fromJSON(request.json)db.session.add(user)db.session.commit()return jsonify({'Success': 1})else:return jsonify({'Success': 2})except Exception:return jsonify({'Success': 3})
Answer

Yes, this is entirely possible - the wtforms.Form constructor takes any MultiDict like interface (it just needs to have getlist), so you can just create an instance of werkzeug.datastructures.MultiDict from your JSON:

data = MultiDict(mapping=request.json)
form = YourForm(data)
if form.validate():# Data is correct

(assuming the field names match) and things will just work.

https://en.xdnf.cn/q/70030.html

Related Q&A

How to install graph-tool for Anaconda Python 3.5 on linux-64?

Im trying to install graph-tool for Anaconda Python 3.5 on Ubuntu 14.04 (x64), but it turns out thats a real trick.I tried this approach, but run into the problem:The following specifications were foun…

How to quickly encrypt a password string in Django without an User Model?

Based on my current Django app settings, is there a function or a snippet that allows me to view the encrypted password, given a raw string? I am testing some functionality and this would be useful fo…

Embedding multiple gridspec layouts on a single matplotlib figure?

I am using the python graphing library matplotlib to graph several things in a report, and I found myself needing to have several fixed-count graphs above an arbitrary grid of smaller graphs. I search…

Writing integers in binary to file in python

How can I write integers to a file in binary in Python 3?For example, I want to write 6277101735386680763835789423176059013767194773182842284081 to a file in binary in exactly 24 bytes (unsigned, I wi…

Dropping some columns when using to_csv in pandas

I have a data frame which I want to write to tow files, one that contains all of the columns and one that has only a subset of the columns So for this data frame: Out_dataOut[9]: A B …

Setting Max Results in API v4 (python)

In v3 of the API Im seeing that there was a max-results parameter that could be passed to get more than 1000 records. I havent been able to figure out how to pass that parameter in v4 of the API using …

Extract text between two different tags beautiful soup

Im trying to extract the text content of the article from this web page.Im just trying to extract the article content and not the "About the author part".The problem is that all the content a…

Add column to pandas without headers

How does one append a column of constant values to a pandas dataframe without headers? I want to append the column at the end.With headers I can do it this way:df[new] = pd.Series([0 for x in range(le…

Replace NaN values of pandas.DataFrame with values from list

In a python script using the library pandas, I have a dataset of lets say 100 lines with a feature "X", containing 36 NaN values, and a list of size 36.I want to replace all the 36 missing va…

Boring Factorials in python

I am trying to understand and solve the following problem :Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friendhas be…