user61629 user61629 - 2 months ago 18
Python Question

How to access preexisting table with Sqlalchemy

I'm working with scrapy. I want to get access to a sqlalchemy session for a table with a table named 'contacts' according to the docs (http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session ) I have created the following:

engine = create_engine('sqlite:///data.db')
# create a configured "Session" class
Session = sessionmaker(bind=engine)

# create a Session
session = Session()

class ContactSpider(Spider):
.......

def parse(self, response):

print('hello')
session.query(contacts).filter_by(name='ed').all()


However I am not seeing a way to connect to a preexisting table. How is this done?

Answer

You can connect to pre-existing tables via reflection. Unfortunately your question lacks some of the code setup, so below is a general pseudocode example (assuming your table name is contacts)

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
# Look up the existing tables from database
Base.metadata.reflect(engine)

# Create class that maps via ORM to the database table
Contact = type('Contact', (Base,), {'__tablename__': 'contacts'})