I'm writing a scraper with scrapy, sqlalchemy and postgres. I'd like the script to check for new items and, if there are any, send an email and write to database. I thought of two tables- one permanent, and one temporary, dropped after its data is processed. I'd like to check if items in the temporary exist in the permanent list, and if not- write them to pernament list. How do I construct the expression to check if the results exist in the other table, with sqlalchemy? I can successfuly write to both of the tables, but I struggle with the next stage is to check for a change and write new items to the permanent table.
Here's the model for table:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
from . import settings
from random import randint
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database connection using database settings from settings.py.
Returns sqlalchemy engine instance
"""
return create_engine(URL(**settings.DATABASE))
def create_item_table(engine):
""""""
DeclarativeBase.metadata.create_all(engine)
class ItemsTemplateTable(object):
def uid(self):
return randint(100, 999999999)
"""Sqlalchemy items table model"""
uid = Column('uid',Integer, default=uid, primary_key=True, unique=True)
item_name = Column('id', String)
item_size = Column('title', String)
item_prize = Column('url', String, nullable=True)
class Items(ItemsTemplateTable, DeclarativeBase):
__tablename__ = "items"
class AllItems(ItemsTemplateTable, DeclarativeBase):
__tablename__ = "allitems"
Here's the pipeline
from sqlalchemy.orm import sessionmaker
from sqlalchemy import literal, select, text, exists
from sqlalchemy.sql import exists
from .models import Items, db_connect, create_items_table
from .items import ItemssItem
class ItemsPipeline(object):
'''Pipeline for storing data from scraped items into a database'''
def __init__(self):
'''
Initialises connection with the database
Creates a table.
'''
engine = db_connect()
create_items_table(engine)
self.Session = sessionmaker(bind=engine)
def process_item(self, item, spider):
session = self.Session()
list = Items(**item)
try:
session.add(list)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return list