Skip to main content

Active Record like validation on SQLAlchemy declarative model objects

Project description

Introduction

SAValidation facilitates Active Record like validation on SQLAlchemy declarative model objects.

You can install the in-development version of savalidation with easy_install savalidation==dev.

The home page is currently the bitbucket repository.

Usage Example

The following is a snippet from the examples.py file:

from datetime import datetime
import formencode
import sqlalchemy as sa
import sqlalchemy.ext.declarative as sadec
import sqlalchemy.sql as sasql
import sqlalchemy.orm as saorm

from savalidation import declarative_base, ValidatingSessionExtension, \
    ValidationError, ValidationMixin
import savalidation.validators as val

engine = sa.create_engine('sqlite://')
meta = sa.MetaData()
Base = declarative_base(metadata=meta)

Session = saorm.scoped_session(
    saorm.sessionmaker(
        bind=engine,
        autoflush=False,
        extension=ValidatingSessionExtension()
    )
)

sess = Session

class Family(Base, ValidationMixin):
    __tablename__ = 'families'

    # SA COLUMNS
    id = sa.Column(sa.Integer, primary_key=True)
    createdts = sa.Column(sa.DateTime, nullable=False, default=datetime.now, server_default=sasql.text('CURRENT_TIMESTAMP'))
    updatedts = sa.Column(sa.DateTime, onupdate=datetime.now)
    name =  sa.Column(sa.Unicode(75), nullable=False, unique=True)
    reg_num = sa.Column(sa.Integer, nullable=False, unique=True)
    status =  sa.Column(sa.Unicode(15), nullable=False, default=u'active', server_default=u'active')

    # VALIDATION
    STATUS_CHOICES = (
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('moved', 'Moved'),
    )
    # will validate nullability & length of string types
    val.validates_constraints()
    val.validates_one_of('status', [k for k, v in STATUS_CHOICES])

    #OTHER
    def __str__(self):
        return '<Family id=%s, name=%s>' % (self.id, self.name)

class Person(Base, ValidationMixin):
    __tablename__ = 'people'

    id = sa.Column(sa.Integer, primary_key=True)
    createdts = sa.Column(sa.DateTime, nullable=False, server_default=sasql.text('CURRENT_TIMESTAMP'))
    updatedts = sa.Column(sa.DateTime, onupdate=datetime.now)
    name_first = sa.Column(sa.Unicode(75), nullable=False)
    name_last = sa.Column(sa.Unicode(75), nullable=False)
    family_role = sa.Column(sa.Unicode(20), nullable=False)
    nullable_but_required = sa.Column(sa.Unicode(5))
    birthdate = sa.Column(sa.Date)

    ROLE_CHOICES = (
        ('father', 'Father'),
        ('mother', 'Mother'),
        ('child', 'Child'),
    )
    val.validates_constraints(exclude='createdts')
    val.validates_presence_of('nullable_but_required')
    val.validates_choices('family_role', ROLE_CHOICES)
    # will automatically convert the string to a python datetime.date object
    val.converts_date('birthdate')

See more examples in the tests directory of the distribution.

Installing & Testing Source

(this is one way, there are others)

  1. create a virtualenv

  2. activate the virtualenv

  3. pip install -e "hg+http://bitbucket.org/rsyring/sqlalchemy-validation#egg=savlidation-dev"

  4. pip install nose

  5. cd src/savalidation/savalidation

  6. nosetests

Questions & Comments

Please visit: http://groups.google.com/group/blazelibs

Dependencies

  • SQLAlchemy

  • FormEncode

  • python-dateutil (for date/time converters)

  • Nose (if you want to run the tests)

Credits

This project borrows code and ideas from:

Current Status

The code itself seems stable, but the API is likely to change in the future.

Change Log

0.1.4 released 2011-05-19

  • change python-dateutil dependence to < 2.0, 2.x is for python 3

0.1.3 released 2011-05-19

  • change SQLAlchemy requirement so the latest package < 0.7 is installed

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

SAValidation-0.1.4.tar.gz (13.2 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page