Skip to content

Instantly share code, notes, and snippets.

@davewsmith
Last active August 1, 2019 20:13
Show Gist options
  • Save davewsmith/6d837cc7e0956fd1e6e2edc6c94f1906 to your computer and use it in GitHub Desktop.
Save davewsmith/6d837cc7e0956fd1e6e2edc6c94f1906 to your computer and use it in GitHub Desktop.
Flask testbed for coaxing SQLAchemy into making the query that you know how to do in raw SQL
#!/usr/bin/env python3
"""
Test bed for flask-sqlalchemy queries
As in, "I know the SQL I want. Can I coax SQLAlchemy into giving it to me?"
"""
from contextlib import contextmanager
from app import create_app, db
from app.models import *
from config import Config
class TestConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
@contextmanager
def environment():
"""
Context manager fsetting up/tearing down the app and
database environment, because fiddly.
"""
try:
app = create_app(TestConfig)
app_context = app.app_context()
app_context.push()
db.create_all()
yield
finally:
db.session.remove()
db.drop_all()
app_context.pop()
with environment():
# Here's where the fun happens
query = "Stab at a query goes here" # e.g., SomeModel.query.join(SomeOtherModel).filter(...)
print(str(query))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment