Skip to content

Instantly share code, notes, and snippets.

@timfreund
Created July 25, 2014 21:36
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 timfreund/ede035810dd6df769f6a to your computer and use it in GitHub Desktop.
Save timfreund/ede035810dd6df769f6a to your computer and use it in GitHub Desktop.
Run a query against a raw connection from SQLAlchemy
from sqlalchemy import create_engine
class SQLKeyring:
"""A SQLKeyring object provides a tiny bit of glue between
the secure credential storage of the Python Keyring Lib and
the database connectivity of SQLAlchemy
"""
def get_connection_url(self, name):
return self.keyring.get_password('sqlkeyring', name)
def get_engine(self, name, **options):
return create_engine(self.get_connection_url(name), **options)
def run_query(query, connection, output_file=sys.stdout, row_prefix=None):
out = csv.writer(output_file)
results = connection.execute(query)
for row in results.fetchall():
if row_prefix is not None:
newrow = [row_prefix]
for v in row:
newrow.append(v)
out.writerow(newrow)
else:
out.writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment