Skip to content

Instantly share code, notes, and snippets.

@m1yag1
Last active April 27, 2018 21:32
Show Gist options
  • Save m1yag1/a51b7751c4603012cd6585bafdd785d3 to your computer and use it in GitHub Desktop.
Save m1yag1/a51b7751c4603012cd6585bafdd785d3 to your computer and use it in GitHub Desktop.
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
def create_sa_connection(connection):
engine = create_engine(connection, echo=False)
Session = sessionmaker(bind=engine)
return engine, session()
# The connection string for connecting to the database
connection_string = 'postgresql+psycopg2://db_user:db_password@localhost:5432/db'
# Get the engine and the session we need to use engine for core and session for orm
engine, session = create_sa_connection(connection_string)
# Reflect the database to allow for declarative and using core
Base = automap_base()
Base.prepare(engine, reflect=True)
# Create a class for a specific table
User = Base.classes.users
# Write a query to get those users
users = session.query(User).all()
# Display all the user emails in the Users table
for user in users:
print(user.email)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment