Add NopaqueForm as a base for all others

This commit is contained in:
Patrick Jentsch 2023-03-29 09:25:08 +02:00
parent 9de09519d6
commit 9b2353105e
13 changed files with 57 additions and 76 deletions

View File

@ -1,9 +1,9 @@
from app.models import Role
from flask_wtf import FlaskForm
from wtforms import BooleanField, SelectField, SubmitField from wtforms import BooleanField, SelectField, SubmitField
from app.forms import NopaqueForm
from app.models import Role
class AdminEditUserForm(FlaskForm): class AdminEditUserForm(NopaqueForm):
confirmed = BooleanField('Confirmed') confirmed = BooleanField('Confirmed')
role = SelectField('Role') role = SelectField('Role')
submit = SubmitField('Submit') submit = SubmitField('Submit')

View File

@ -1,4 +1,3 @@
from flask_wtf import FlaskForm
from wtforms import ( from wtforms import (
BooleanField, BooleanField,
PasswordField, PasswordField,
@ -7,11 +6,12 @@ from wtforms import (
ValidationError ValidationError
) )
from wtforms.validators import InputRequired, Email, EqualTo, Length, Regexp from wtforms.validators import InputRequired, Email, EqualTo, Length, Regexp
from app.forms import NopaqueForm
from app.models import User from app.models import User
from . import USERNAME_REGEX from . import USERNAME_REGEX
class RegistrationForm(FlaskForm): class RegistrationForm(NopaqueForm):
email = StringField( email = StringField(
'Email', 'Email',
validators=[InputRequired(), Email(), Length(max=254)] validators=[InputRequired(), Email(), Length(max=254)]
@ -55,19 +55,19 @@ class RegistrationForm(FlaskForm):
raise ValidationError('Username already in use') raise ValidationError('Username already in use')
class LoginForm(FlaskForm): class LoginForm(NopaqueForm):
user = StringField('Email or username', validators=[InputRequired()]) user = StringField('Email or username', validators=[InputRequired()])
password = PasswordField('Password', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()])
remember_me = BooleanField('Keep me logged in') remember_me = BooleanField('Keep me logged in')
submit = SubmitField() submit = SubmitField()
class ResetPasswordRequestForm(FlaskForm): class ResetPasswordRequestForm(NopaqueForm):
email = StringField('Email', validators=[InputRequired(), Email()]) email = StringField('Email', validators=[InputRequired(), Email()])
submit = SubmitField() submit = SubmitField()
class ResetPasswordForm(FlaskForm): class ResetPasswordForm(NopaqueForm):
password = PasswordField( password = PasswordField(
'New password', 'New password',
validators=[ validators=[

View File

@ -34,7 +34,7 @@ def before_request():
def register(): def register():
if current_user.is_authenticated: if current_user.is_authenticated:
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
form = RegistrationForm(prefix='registration-form') form = RegistrationForm()
if form.validate_on_submit(): if form.validate_on_submit():
try: try:
user = User.create( user = User.create(
@ -70,7 +70,7 @@ def register():
def login(): def login():
if current_user.is_authenticated: if current_user.is_authenticated:
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
form = LoginForm(prefix='login-form') form = LoginForm()
if form.validate_on_submit(): if form.validate_on_submit():
user = User.query.filter((User.email == form.user.data.lower()) | (User.username == form.user.data)).first() user = User.query.filter((User.email == form.user.data.lower()) | (User.username == form.user.data)).first()
if user and user.verify_password(form.password.data): if user and user.verify_password(form.password.data):
@ -144,7 +144,7 @@ def confirm(token):
def reset_password_request(): def reset_password_request():
if current_user.is_authenticated: if current_user.is_authenticated:
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
form = ResetPasswordRequestForm(prefix='reset-password-request-form') form = ResetPasswordRequestForm()
if form.validate_on_submit(): if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data.lower()).first() user = User.query.filter_by(email=form.email.data.lower()).first()
if user is not None: if user is not None:
@ -174,7 +174,7 @@ def reset_password_request():
def reset_password(token): def reset_password(token):
if current_user.is_authenticated: if current_user.is_authenticated:
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
form = ResetPasswordForm(prefix='reset-password-form') form = ResetPasswordForm()
if form.validate_on_submit(): if form.validate_on_submit():
if User.reset_password(token, form.password.data): if User.reset_password(token, form.password.data):
db.session.commit() db.session.commit()

View File

@ -1,4 +1,3 @@
from flask_wtf import FlaskForm
from wtforms import ( from wtforms import (
StringField, StringField,
SubmitField, SubmitField,
@ -6,9 +5,10 @@ from wtforms import (
IntegerField IntegerField
) )
from wtforms.validators import InputRequired, Length from wtforms.validators import InputRequired, Length
from app.forms import NopaqueForm
class ContributionBaseForm(FlaskForm): class ContributionBaseForm(NopaqueForm):
title = StringField( title = StringField(
'Title', 'Title',
validators=[InputRequired(), Length(max=64)] validators=[InputRequired(), Length(max=64)]

View File

@ -27,8 +27,7 @@ def spacy_nlp_pipeline_models():
@register_breadcrumb(bp, '.spacy_nlp_pipeline_models.create', 'Create') @register_breadcrumb(bp, '.spacy_nlp_pipeline_models.create', 'Create')
@login_required @login_required
def create_spacy_nlp_pipeline_model(): def create_spacy_nlp_pipeline_model():
form_prefix = 'create-spacy-nlp-pipeline-model-form' form = CreateSpaCyNLPPipelineModelForm()
form = CreateSpaCyNLPPipelineModelForm(prefix=form_prefix)
if form.is_submitted(): if form.is_submitted():
if not form.validate(): if not form.validate():
return {'errors': form.errors}, 400 return {'errors': form.errors}, 400
@ -64,11 +63,7 @@ def create_spacy_nlp_pipeline_model():
@login_required @login_required
def spacy_nlp_pipeline_model(spacy_nlp_pipeline_model_id): def spacy_nlp_pipeline_model(spacy_nlp_pipeline_model_id):
snpm = SpaCyNLPPipelineModel.query.get_or_404(spacy_nlp_pipeline_model_id) snpm = SpaCyNLPPipelineModel.query.get_or_404(spacy_nlp_pipeline_model_id)
form_prefix = 'edit-spacy-nlp-pipeline-model-form' form = EditSpaCyNLPPipelineModelForm(data=snpm.to_json_serializeable())
form = EditSpaCyNLPPipelineModelForm(
data=snpm.to_json_serializeable(),
prefix=form_prefix
)
if form.validate_on_submit(): if form.validate_on_submit():
form.populate_obj(snpm) form.populate_obj(snpm)
if db.session.is_modified(snpm): if db.session.is_modified(snpm):

View File

@ -27,8 +27,7 @@ def tesseract_ocr_pipeline_models():
@register_breadcrumb(bp, '.tesseract_ocr_pipeline_models.create', 'Create') @register_breadcrumb(bp, '.tesseract_ocr_pipeline_models.create', 'Create')
@login_required @login_required
def create_tesseract_ocr_pipeline_model(): def create_tesseract_ocr_pipeline_model():
form_prefix = 'create-tesseract-ocr-pipeline-model-form' form = CreateTesseractOCRPipelineModelForm()
form = CreateTesseractOCRPipelineModelForm(prefix=form_prefix)
if form.is_submitted(): if form.is_submitted():
if not form.validate(): if not form.validate():
return {'errors': form.errors}, 400 return {'errors': form.errors}, 400
@ -63,11 +62,7 @@ def create_tesseract_ocr_pipeline_model():
@login_required @login_required
def tesseract_ocr_pipeline_model(tesseract_ocr_pipeline_model_id): def tesseract_ocr_pipeline_model(tesseract_ocr_pipeline_model_id):
topm = TesseractOCRPipelineModel.query.get_or_404(tesseract_ocr_pipeline_model_id) topm = TesseractOCRPipelineModel.query.get_or_404(tesseract_ocr_pipeline_model_id)
form_prefix = 'edit-tesseract-ocr-pipeline-model-form' form = EditTesseractOCRPipelineModelForm(data=topm.to_json_serializeable())
form = EditTesseractOCRPipelineModelForm(
data=topm.to_json_serializeable(),
prefix=form_prefix
)
if form.validate_on_submit(): if form.validate_on_submit():
form.populate_obj(topm) form.populate_obj(topm)
if db.session.is_modified(topm): if db.session.is_modified(topm):

View File

@ -1,4 +1,3 @@
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired from flask_wtf.file import FileField, FileRequired
from wtforms import ( from wtforms import (
StringField, StringField,
@ -7,9 +6,10 @@ from wtforms import (
IntegerField IntegerField
) )
from wtforms.validators import InputRequired, Length from wtforms.validators import InputRequired, Length
from app.forms import NopaqueForm
class CorpusFileBaseForm(FlaskForm): class CorpusFileBaseForm(NopaqueForm):
author = StringField( author = StringField(
'Author', 'Author',
validators=[InputRequired(), Length(max=255)] validators=[InputRequired(), Length(max=255)]
@ -37,18 +37,10 @@ class CorpusFileBaseForm(FlaskForm):
class CreateCorpusFileForm(CorpusFileBaseForm): class CreateCorpusFileForm(CorpusFileBaseForm):
vrt = FileField('File', validators=[FileRequired()]) vrt = FileField('File', validators=[FileRequired()])
def __init__(self, *args, **kwargs):
if 'prefix' not in kwargs:
kwargs['prefix'] = 'create-corpus-file-form'
super().__init__(*args, **kwargs)
def validate_vrt(self, field): def validate_vrt(self, field):
if not field.data.filename.lower().endswith('.vrt'): if not field.data.filename.lower().endswith('.vrt'):
raise ValidationError('VRT files only!') raise ValidationError('VRT files only!')
class UpdateCorpusFileForm(CorpusFileBaseForm): class UpdateCorpusFileForm(CorpusFileBaseForm):
def __init__(self, *args, **kwargs): pass
if 'prefix' not in kwargs:
kwargs['prefix'] = 'update-corpus-file-form'
super().__init__(*args, **kwargs)

View File

@ -1,9 +1,9 @@
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import InputRequired, Length from wtforms.validators import InputRequired, Length
from app.forms import NopaqueForm
class CorpusBaseForm(FlaskForm): class CorpusBaseForm(NopaqueForm):
description = TextAreaField( description = TextAreaField(
'Description', 'Description',
validators=[InputRequired(), Length(max=255)] validators=[InputRequired(), Length(max=255)]
@ -13,18 +13,12 @@ class CorpusBaseForm(FlaskForm):
class CreateCorpusForm(CorpusBaseForm): class CreateCorpusForm(CorpusBaseForm):
def __init__(self, *args, **kwargs): pass
if 'prefix' not in kwargs:
kwargs['prefix'] = 'create-corpus-form'
super().__init__(*args, **kwargs)
class UpdateCorpusForm(CorpusBaseForm): class UpdateCorpusForm(CorpusBaseForm):
def __init__(self, *args, **kwargs): pass
if 'prefix' not in kwargs:
kwargs['prefix'] = 'update-corpus-form'
super().__init__(*args, **kwargs) class ImportCorpusForm(NopaqueForm):
class ImportCorpusForm(FlaskForm):
pass pass

9
app/forms.py Normal file
View File

@ -0,0 +1,9 @@
from flask_wtf import FlaskForm
import re
class NopaqueForm(FlaskForm):
def __init__(self, *args, **kwargs):
if 'prefix' not in kwargs:
kwargs['prefix'] = re.sub(r'(?<!^)(?=[A-Z])', '-', self.__class__.__name__).lower()
super().__init__(*args, **kwargs)

View File

@ -9,7 +9,7 @@ from . import bp
@bp.route('', methods=['GET', 'POST']) @bp.route('', methods=['GET', 'POST'])
@register_breadcrumb(bp, '.', '<i class="material-icons">home</i>') @register_breadcrumb(bp, '.', '<i class="material-icons">home</i>')
def index(): def index():
form = LoginForm(prefix='login-form') form = LoginForm()
if form.validate_on_submit(): if form.validate_on_submit():
user = User.query.filter((User.email == form.user.data.lower()) | (User.username == form.user.data)).first() user = User.query.filter((User.email == form.user.data.lower()) | (User.username == form.user.data)).first()
if user and user.verify_password(form.password.data): if user and user.verify_password(form.password.data):

View File

@ -1,16 +1,21 @@
from flask_login import current_user from flask_login import current_user
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired from flask_wtf.file import FileField, FileRequired
from wtforms import (BooleanField, DecimalRangeField, MultipleFileField, from wtforms import (
SelectField, StringField, SubmitField, ValidationError) BooleanField,
DecimalRangeField,
MultipleFileField,
SelectField,
StringField,
SubmitField,
ValidationError
)
from wtforms.validators import InputRequired, Length from wtforms.validators import InputRequired, Length
from app.forms import NopaqueForm
from app.models import SpaCyNLPPipelineModel, TesseractOCRPipelineModel from app.models import SpaCyNLPPipelineModel, TesseractOCRPipelineModel
from . import SERVICES from . import SERVICES
class CreateJobBaseForm(FlaskForm): class CreateJobBaseForm(NopaqueForm):
description = StringField( description = StringField(
'Description', 'Description',
validators=[InputRequired(), Length(max=255)] validators=[InputRequired(), Length(max=255)]

View File

@ -35,7 +35,7 @@ def file_setup_pipeline():
version = request.args.get('version', service_manifest['latest_version']) version = request.args.get('version', service_manifest['latest_version'])
if version not in service_manifest['versions']: if version not in service_manifest['versions']:
abort(404) abort(404)
form = CreateFileSetupPipelineJobForm(prefix='create-job-form', version=version) form = CreateFileSetupPipelineJobForm(version=version)
if form.is_submitted(): if form.is_submitted():
if not form.validate(): if not form.validate():
response = {'errors': form.errors} response = {'errors': form.errors}
@ -77,7 +77,7 @@ def tesseract_ocr_pipeline():
version = request.args.get('version', service_manifest['latest_version']) version = request.args.get('version', service_manifest['latest_version'])
if version not in service_manifest['versions']: if version not in service_manifest['versions']:
abort(404) abort(404)
form = CreateTesseractOCRPipelineJobForm(prefix='create-job-form', version=version) form = CreateTesseractOCRPipelineJobForm(version=version)
if form.is_submitted(): if form.is_submitted():
if not form.validate(): if not form.validate():
response = {'errors': form.errors} response = {'errors': form.errors}
@ -140,7 +140,6 @@ def transkribus_htr_pipeline():
print(transkribus_htr_pipeline_models[len(transkribus_htr_pipeline_models)-1]) print(transkribus_htr_pipeline_models[len(transkribus_htr_pipeline_models)-1])
form = CreateTranskribusHTRPipelineJobForm( form = CreateTranskribusHTRPipelineJobForm(
transkribus_htr_pipeline_models=transkribus_htr_pipeline_models, transkribus_htr_pipeline_models=transkribus_htr_pipeline_models,
prefix='create-job-form',
version=version version=version
) )
if form.is_submitted(): if form.is_submitted():
@ -187,7 +186,7 @@ def spacy_nlp_pipeline():
version = request.args.get('version', SERVICES[service]['latest_version']) version = request.args.get('version', SERVICES[service]['latest_version'])
if version not in service_manifest['versions']: if version not in service_manifest['versions']:
abort(404) abort(404)
form = CreateSpacyNLPPipelineJobForm(prefix='create-job-form', version=version) form = CreateSpacyNLPPipelineJobForm(version=version)
spacy_nlp_pipeline_models = SpaCyNLPPipelineModel.query.all() spacy_nlp_pipeline_models = SpaCyNLPPipelineModel.query.all()
if form.is_submitted(): if form.is_submitted():
if not form.validate(): if not form.validate():

View File

@ -1,5 +1,4 @@
from flask_login import current_user from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import ( from wtforms import (
FileField, FileField,
PasswordField, PasswordField,
@ -16,12 +15,13 @@ from wtforms.validators import (
Length, Length,
Regexp Regexp
) )
from app.forms import NopaqueForm
from app.models import User, UserSettingJobStatusMailNotificationLevel from app.models import User, UserSettingJobStatusMailNotificationLevel
from app.auth import USERNAME_REGEX from app.auth import USERNAME_REGEX
from app.wtf_validators import FileSizeLimit from app.wtf_validators import FileSizeLimit
class EditAccountForm(FlaskForm): class EditAccountForm(NopaqueForm):
email = StringField( email = StringField(
'E-Mail', 'E-Mail',
validators=[DataRequired(), Length(max=254), Email()] validators=[DataRequired(), Length(max=254), Email()]
@ -46,8 +46,6 @@ class EditAccountForm(FlaskForm):
user = kwargs.get('user', current_user._get_current_object()) user = kwargs.get('user', current_user._get_current_object())
if 'data' not in kwargs: if 'data' not in kwargs:
kwargs['data'] = user.to_json_serializeable() kwargs['data'] = user.to_json_serializeable()
if 'prefix' not in kwargs:
kwargs['prefix'] = 'edit-profile-settings-form'
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.user = user self.user = user
@ -65,7 +63,7 @@ class EditAccountForm(FlaskForm):
return self.submit.data and self.validate() return self.submit.data and self.validate()
class EditProfileForm(FlaskForm): class EditProfileForm(NopaqueForm):
avatar = FileField( avatar = FileField(
'Image File', 'Image File',
[FileSizeLimit(max_size_in_mb=2)] [FileSizeLimit(max_size_in_mb=2)]
@ -104,8 +102,6 @@ class EditProfileForm(FlaskForm):
if 'data' not in kwargs: if 'data' not in kwargs:
user = current_user._get_current_object() user = current_user._get_current_object()
kwargs['data'] = user.to_json_serializeable() kwargs['data'] = user.to_json_serializeable()
if 'prefix' not in kwargs:
kwargs['prefix'] = 'edit-public-profile-information-form'
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def validate_image_file(self, field): def validate_image_file(self, field):
@ -116,7 +112,7 @@ class EditProfileForm(FlaskForm):
return self.submit.data and self.validate() return self.submit.data and self.validate()
class ChangePasswordForm(FlaskForm): class ChangePasswordForm(NopaqueForm):
password = PasswordField('Old password', validators=[DataRequired()]) password = PasswordField('Old password', validators=[DataRequired()])
new_password = PasswordField( new_password = PasswordField(
'New password', 'New password',
@ -136,8 +132,6 @@ class ChangePasswordForm(FlaskForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
user = kwargs.get('user', current_user._get_current_object()) user = kwargs.get('user', current_user._get_current_object())
if 'prefix' not in kwargs:
kwargs['prefix'] = 'change-password-form'
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.user = user self.user = user
@ -149,7 +143,7 @@ class ChangePasswordForm(FlaskForm):
return self.submit.data and self.validate() return self.submit.data and self.validate()
class EditNotificationsForm(FlaskForm): class EditNotificationsForm(NopaqueForm):
job_status_mail_notification_level = SelectField( job_status_mail_notification_level = SelectField(
'Job status mail notification level', 'Job status mail notification level',
choices=[ choices=[
@ -164,8 +158,6 @@ class EditNotificationsForm(FlaskForm):
if 'data' not in kwargs: if 'data' not in kwargs:
user = current_user._get_current_object() user = current_user._get_current_object()
kwargs['data'] = user.to_json_serializeable() kwargs['data'] = user.to_json_serializeable()
if 'prefix' not in kwargs:
kwargs['prefix'] = 'edit-notification-settings-form'
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def validate_on_submit(self): def validate_on_submit(self):