Skip to content

Instantly share code, notes, and snippets.

@jennielees
Created June 3, 2015 00:13
Show Gist options
  • Save jennielees/1801044b5c2975a358d1 to your computer and use it in GitHub Desktop.
Save jennielees/1801044b5c2975a358d1 to your computer and use it in GitHub Desktop.
Converting the users from week 4 into SQLAlchemy objects
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Set up the SQLAlchemy Database to be a local file 'users.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
if __name__ == "__main__":
# We need to make sure Flask knows about its views before we run
# the app, so we import them. We could do it earlier, but there's
# a risk that we may run into circular dependencies, so we do it at the
# last minute here.
from views import *
app.run(debug=True)
""" Test file for models.py.
When models.py is complete, this file should completely pass.
NOTE:
To make these tests accurate, this file DELETES all content in the
database first.
"""
import traceback
from users import *
def check_test(func):
""" This is a decorator that simply prints out whether the function
it calls succeeded or not. You don't need to edit this.
"""
def func_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
print ":) {} passed".format(func.__name__)
except AssertionError:
traceback.print_exc()
print ":( {} failed".format(func.__name__)
return func_wrapper
@check_test
def test_connection():
# No longer needed, but let's update this to delete everything so we can
# test
User.query.delete()
db.session.commit()
@check_test
def test_create():
# Test that the create user function finishes cleanly
result = create_user('test', 'test', 'test', 'test', 'test')
# assert is a special Python keyword that throws an error if the thing it
# is testing turns out not to be True. Our check_test decorator looks for
# errors and tells us the test failed if it found any errors like this.
assert result is not None
assert isinstance(result, User)
assert result.username == 'test'
@check_test
def test_create_worked():
result = get_user_by_username('test')
assert result is not None
@check_test
def test_get_user_by_id():
result = get_user(1)
assert result is not None
@check_test
def test_list_users():
result = list_users()
assert isinstance(result, list) # isinstance says "is it of this type"
assert len(result) > 0
@check_test
def test_update_user():
result = update_user(1, password='newpass')
assert result is not None
assert isinstance(result, User)
assert result.password == 'newpass'
for item in dir():
""" Loop through all the defined items we know about (functions, etc).
If the name starts with test_, assume it's a test function and run it!
"""
if item.startswith('test_'):
globals()[item]()
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100))
password = db.Column(db.String(100))
email = db.Column(db.String(250))
realname = db.Column(db.String(100))
avatar = db.Column(db.String(250))
def __init__(self, username, password, email, realname, avatar):
self.username = username
self.password = password
self.email = email
self.realname = realname
self.avatar = avatar
def list_users():
return User.query.all()
def get_user(id):
return User.query.get(id)
def get_user_by_username(username):
return User.query.filter_by(username=username).first()
def create_user(username, email, password, realname, avatar):
user = User(username, email, password, realname, avatar)
db.session.add(user)
db.session.commit()
return user
def update_user(id, username=None, email=None, password=None, realname=None,
avatar=None):
# This one is harder with the object syntax actually! So we changed the
# function definition.
user = User.query.get(id)
if username:
user.username = username
if email:
user.email = email
if password:
user.password = password
if realname:
user.realname = realname
if avatar:
user.avatar = avatar
db.session.commit()
return user
if __name__ == "__main__":
db.create_all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment