Skip to content

Instantly share code, notes, and snippets.

@icook
Last active December 18, 2015 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icook/5758971 to your computer and use it in GitHub Desktop.
Save icook/5758971 to your computer and use it in GitHub Desktop.
SQLAlchemy + Yota example
# /// Import SQLAlchmey and flask...
import yota
from yota.nodes import *
from yota.validators import *
""" Say we have a simple SQLAlchemy table like such """
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
email = Column(String(120), unique=True)
def __init__(self, name=None, email=None):
self.name = name
self.email = email
""" And we want to create a Form to make a new user. We need a place for them to enter a name and an email """
class UserForm(yota.Form):
name = EntryNode()
_name_length = Check(MaxLengthValidator(15), 'name')
email = EntryNode()
_email_format = Check(EmailValidator(), 'email')
""" Now we have a simple flask view like so... """
@app.route("/", methods=['GET', 'POST'])
def home():
# Make an instance of the form
f = UserForm()
# Handle submission of the form
if request.method == 'POST':
form_out = f.validate_render(request.form)
if (form_out): # validate render passes true if validation passes
""" we want to create a new sql alch object. Note that we are accessing the actual Node objects inside the form
object. Nodes are maintained as attributes, and when the validation was run the data from the submission is
now inside the data attribute of the node """
u = User(name=f.name.data, email=f.email.data)
else:
# Just render the form regularly if they're not submitting
form_out = f.render()
return render_template('index.html',
form=form_out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment