Skip to content

Instantly share code, notes, and snippets.

@DazWorrall
Created April 6, 2013 12:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DazWorrall/5325897 to your computer and use it in GitHub Desktop.
Save DazWorrall/5325897 to your computer and use it in GitHub Desktop.
SQLAlchemy 'or' operator
from flask import Flask, request
from flask.ext.sqlalchemy import SQLAlchemy
import unittest
app = Flask(__name__)
app.debug = True
db = SQLAlchemy()
db.init_app(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(length=100))
email = db.Column(db.String(length=100))
@app.route('/', methods=['POST'])
def count():
name = request.form.get('username')
email = request.form.get('email')
result = User.query.filter((User.username == name) | (User.email == email))
return str(result.count())
class TestUserLookup(unittest.TestCase):
def setUp(self):
with app.app_context():
db.create_all()
self.u1 = User(username='bob', email='bob@test.com')
self.u2 = User(username='frank', email='frank@test.com')
db.session.add(self.u1)
db.session.add(self.u2)
db.session.commit()
self.client = app.test_client()
def tearDown(self):
with app.app_context():
db.drop_all()
def make_request(self, username, email):
return self.client.post(
'/',
data = {
'username': username,
'email': email,
}
)
def test_no_match(self):
resp = self.make_request('jeff', 'jeff@test.com')
self.assertEqual('0', resp.data)
def test_user_match(self):
resp = self.make_request('bob', 'jeff@test.com')
self.assertEqual('1', resp.data)
def test_email_match(self):
resp = self.make_request('jeff', 'frank@test.com')
self.assertEqual('1', resp.data)
def test_both_match(self):
resp = self.make_request('bob', 'frank@test.com')
self.assertEqual('2', resp.data)
if __name__ == '__main__':
unittest.main()
@vadimuha
Copy link

vadimuha commented Dec 4, 2017

What about and operator?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment