How to access preexisting table with Sqlalchemy
<p>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 (<a href="http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session</a> ) I have created the following: </p>

<pre><code>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()     
</code></pre>

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

<p>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 <code>contacts</code>)</p>

<pre><code>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'})
</code></pre>

python sqlalchemy