Created
July 25, 2014 21:36
-
-
Save timfreund/ede035810dd6df769f6a to your computer and use it in GitHub Desktop.
Run a query against a raw connection from SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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