def test_auto_validators(self): course_form = model_form(self.Course, self.sess)() student_form = model_form(self.Student, self.sess)() assert contains_validator(student_form.dob, Optional) assert contains_validator(student_form.full_name, Required) assert not contains_validator(course_form.has_prereqs, Required) assert not contains_validator(course_form.boolean_nullable, Required)
def test_convert_types(self): form = model_form(self.AllTypesModel)() assert isinstance(form.string, fields.StringField) assert isinstance(form.unicode, fields.StringField) assert isinstance(form.varchar, fields.StringField) assert isinstance(form.postgres_inet, fields.StringField) assert isinstance(form.postgres_macaddr, fields.StringField) assert isinstance(form.postgres_uuid, fields.StringField) assert isinstance(form.mysql_year, fields.StringField) assert isinstance(form.integer, fields.IntegerField) assert isinstance(form.biginteger, fields.IntegerField) assert isinstance(form.smallinteger, fields.IntegerField) assert isinstance(form.numeric, fields.DecimalField) assert isinstance(form.float, fields.DecimalField) assert isinstance(form.text, fields.TextAreaField) assert isinstance(form.binary, fields.TextAreaField) assert isinstance(form.largebinary, fields.TextAreaField) assert isinstance(form.unicodetext, fields.TextAreaField) assert isinstance(form.enum, fields.SelectField) assert isinstance(form.boolean, fields.BooleanField) assert isinstance(form.mssql_bit, fields.BooleanField) assert isinstance(form.datetime, fields.DateTimeField) assert isinstance(form.timestamp, fields.DateTimeField) assert isinstance(form.date, fields.DateField)
def index(): from models import Post post_form_class = model_form(Post, base_class=FlaskForm, db_session=db.session) if request.method == 'POST': form = post_form_class(request.form) if form.validate(): try: post = Post(**form.data) db.session.add(post) db.session.commit() flash('Post created!') except IntegrityError: db.session.rollback() flash("User {} is already exists".format(post.username)) else: flash('Form is not valid! Post was not created.') else: form = post_form_class() posts = Post.query.filter(Post.age > 17).all() return render_template('index.html', form=form, posts=posts)
def test_field_args(self): shared = {"full_name": {"validators": [Regexp("test")]}} student_form = model_form(self.Student, self.sess, field_args=shared)() assert contains_validator(student_form.full_name, Regexp) # original shared field_args should not be modified assert len(shared["full_name"]["validators"]) == 1
def test_field_args(self): shared = {'full_name': {'validators': [Regexp('test')]}} student_form = model_form(self.Student, self.sess, field_args=shared)() assert contains_validator(student_form.full_name, Regexp) # original shared field_args should not be modified assert len(shared['full_name']['validators']) == 1
def index(): from models import Student post_form_class = model_form(Student, base_class=FlaskForm, db_session=db.session) if request.method == 'POST': form = post_form_class(request.form) if form.validate(): try: post = Student(**form.data) db.session.add(post) db.session.commit() flash('Student created!') except IntegrityError: db.session.rollback() flash("User {} is already exists".format(post.studentID)) else: flash('Form is not valid! Student was not created.') else: form = post_form_class() posts = Student.query.all() q = Student.query.filter( or_(and_(Student.sex == 'male', Student.age > 21), (and_(Student.sex == 'female', Student.faculty == 'Philology')))).order_by(Student.age) return render_template('index.html', form=form, posts=posts, q=q)
def get_form_class(self): """Retrieve the form class to instantiate. When :attr:`form_class` is not set, a form class will be automatically generated using :attr:`model` and :attr:`fields`. :returns: form class :rtype: type """ if self.fields is not None and self.form_class: error = ("{0} requires either a definition of 'fields' or " "'form_class', not both") raise RuntimeError(error.format(self.__class__.__name__)) if self.form_class: return self.form_class if self.fields is None: error = ("{0} requires a definition of 'fields' when " "'form_class' is not defined") raise NotImplementedError(error.format(self.__class__.__name__)) return model_form(self.get_model(), session, Form, self.fields)
def test_order_default(self): """Test that fields come out in model order by default.""" form = model_form(self.Model)() self.assertEqual( [field.name for field in form], ['foo', 'bar', 'baz'])
def test_no_mro(self): converter = ModelConverter(use_mro=False) # Without MRO, will not be able to convert 'grade' self.assertRaises(ModelConversionError, model_form, self.Course, self.sess, converter=converter) # If we exclude 'grade' everything should continue working F = model_form(self.Course, self.sess, exclude=['grade'], converter=converter) self.assertEqual(len(list(F())), 8)
def test_no_mro(self): converter = ModelConverter(use_mro=False) # Without MRO, will not be able to convert 'grade' self.assertRaises(ModelConversionError, model_form, self.Course, self.sess, converter=converter) # If we exclude 'grade' everything should continue working F = model_form(self.Course, self.sess, exclude=['grade'], converter=converter) self.assertEqual(len(list(F())), 7)
def create_user(): """ form = MyFlaskForm() if form.validate_on_submit(): return redirect('/list/') """ user = User() data = {"form_errors": []} success = False UserForm = model_form(User) if request.method == 'POST': form = UserForm(request.form, obj=user) if form.validate(): form.populate_obj(user) db.session.add(user) db.session.commit() success = True else: print("FORM ERRORS: ", form.errors) data["form_errors"] = form.errors else: form = UserForm(obj=user) data["success"] = success data["form"] = form return render_template('users/create.html', data=data)
def test_convert_basic(self): self.assertRaises(TypeError, model_form, None) self.assertRaises(ModelConversionError, model_form, self.Course) form_class = model_form(self.Course, exclude=["students"]) form = form_class() self.assertEqual(len(list(form)), 7) assert isinstance(form.cost, fields.DecimalField) assert isinstance(form.has_prereqs, fields.BooleanField) assert isinstance(form.started, fields.DateTimeField)
def test_only_subset(self): """ Test that fields come out in the specified order when all fields are named in `only`. """ form = model_form(self.Model, only=['baz', 'foo'])() self.assertEqual( [field.name for field in form], ['baz', 'foo'])
def test_exclude_order(self): """ Test that fields come out in model order, ignoring excluded fields. """ field_names = ['foo', 'bar', 'baz'] for excluded_field in field_names: form = model_form(self.Model, exclude=[excluded_field])() self.assertEqual( [field.name for field in form], [f for f in field_names if f != excluded_field])
class Car(db.Model): __tablename__ = 'car' id = db.Column(db.Integer, primary_key=True) year = db.Column(db.Integer) make_id = db.Column(db.Integer, db.ForeignKey('make.id')) model = db.Column(db.String(50)) make = db.relationship(Make) def __str__(self): return ' '.join((str(self.year), str(self.make), self.model)) MakeForm = model_form(Make, db_session=db.session) CarForm = model_form(Car, db_session=db.session) @app.route('/make', methods=['GET', 'POST']) def make(): make = Make() success = False if request.method == 'POST': form = MakeForm(request.form, obj=make) if form.validate(): form.populate_obj(make) db.session.add(make) db.session.commit() success = True
def test_column_default_scalar(self): student_form = model_form(self.StudentDefaultScoreScalar, self.sess)() assert not isinstance(student_form._fields['score'].default, ColumnDefault) self.assertEqual(student_form._fields['score'].default, 10)
def test_only(self): desired_fields = ['id', 'cost', 'description'] form = model_form(self.Course, only=desired_fields)() self.assertEqual(len(list(form)), 2) form = model_form(self.Course, only=desired_fields, exclude_pk=False)() self.assertEqual(len(list(form)), 3)
def test_convert_many_to_many(self): student_form = model_form(self.Student, self.sess)() assert isinstance(student_form.courses, QuerySelectMultipleField)
def test_convert_many_to_one(self): student_form = model_form(self.Student, self.sess)() assert isinstance(student_form.current_school, QuerySelectField)
def test_exclude_fk(self): student_form = model_form(self.Student, self.sess)() assert ('current_school_id' not in student_form._fields)
def test_column_default_callable(self): student_form = model_form(self.StudentDefaultScoreCallable, self.sess)() self.assertEqual(student_form._fields['score'].default, 5)
def test_include_fk(self): student_form = model_form(self.Student, self.sess, exclude_fk=False)() assert ('current_school_id' in student_form._fields)
def test_convert_basic(self): self.assertRaises(TypeError, model_form, None) self.assertRaises(ModelConversionError, model_form, self.Course) form_class = model_form(self.Course, exclude=['students']) form = form_class() self.assertEqual(len(list(form)), 7)
def test_convert_one_to_many(self): school_form = model_form(self.School, self.sess)() assert isinstance(school_form.students, QuerySelectMultipleField)
def test_exclude_pk(self): form_class = model_form(self.Student, self.sess, exclude_pk=True) student_form = form_class() assert ('id' not in student_form._fields)
class UserForm(SanicForm, model_form(User, converter=Converter())): pass
def test_include_pk(self): form_class = model_form(self.Student, self.sess, exclude_pk=False) student_form = form_class() assert ('id' in student_form._fields)
def test_auto_validators(self): student_form = model_form(self.Student, self.sess)() assert contains_validator(student_form.dob, Optional) assert contains_validator(student_form.full_name, Required)
app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///sample_db.sqlite" app.config["SQLALCHEMY_ECHO"] = True db = SQLAlchemy(app) class Car(db.Model): __tablename__ = "cars" id = db.Column(db.Integer, primary_key=True) make = db.Column(db.String(50)) model = db.Column(db.String(50)) CarForm = model_form(Car) @app.route("/", methods=["GET", "POST"]) def create_car(): car = Car() success = False if request.method == "POST": form = CarForm(request.form, obj=car) if form.validate(): form.populate_obj(car) db.session.add(car) db.session.commit() success = True else:
def __init__(self): self.form = model_form(self.model, db_session=sql.session)
db.ForeignKey('servico_saude.id'), primary_key=True, nullable=False, index=True)) class Account(db.Model): __tablename__ = 'accounts' id = db.Column(db.Integer, primary_key=True) nome = db.Column(db.String(255), nullable=False) senha = db.Column(db.String(32), nullable=False) email = db.Column(db.String(255), nullable=False) AccountForm = model_form(Account) class Beneficio(db.Model): __tablename__ = 'beneficio' id = db.Column(db.Integer, primary_key=True) beneficio = db.Column(db.String(255), nullable=False) cidadao = db.relationship('Cidadao', secondary='cidadaoxbeneficios', backref='beneficios') class CidadaoxculturaLazer(db.Model): __tablename__ = 'cidadaoxcultura_lazer'
from flask import current_app from flask.ext.wtf import Form from wtforms.fields import FileField from wtforms.validators import Required from wtforms_sqlalchemy.orm import model_form from cidadeiluminada.protocolos.models import Protocolo _protocolos_fields_args = { 'cod_protocolo': { 'validators': [Required()], }, 'cep': { 'validators': [Required()], } } _ProtocoloForm = model_form(Protocolo, field_args=_protocolos_fields_args, base_class=Form, exclude=['timestamp']) class ProtocoloForm(_ProtocoloForm): arquivo_protocolo = FileField(validators=[Required()]) def validate_arquivo_protocolo(self, field): filename = field.data.filename return '.' in filename and filename.rsplit('.', 1)[1] in \ current_app.config['ALLOWED_EXTENSIONS']