1

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?

asked Sep 16, 2016 at 19:04
1
  • Use table/class mapping. Search for "DeclarativeBase" in the doc or tutorial. Commented Sep 16, 2016 at 19:43

1 Answer 1

1

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'})
answered Sep 17, 2016 at 6:54
2
  • Thank you that does work, but I'm having trouble understanding the connection b/w a Session and The model object (Contact). I'll ask a follow up. Also why is it called 'declarative_base' Commented Sep 17, 2016 at 16:20
  • Reflecting declarative model classes automatically is handled already by automap, which will also create relationships etc. I'd highly recommend using it instead of custom dynamic class creation. Commented Sep 17, 2016 at 17:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.