user61629 user61629 - 1 month ago 4x
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 ( ) 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):


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


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

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