简体   繁体   English

如何使用Python和Sqlalchemy检查和写入Postgres

[英]How to check and write to Postgres with Python and Sqlalchemy

I'm writing a scraper with scrapy, sqlalchemy and postgres. 我正在用scrapy,sqlalchemy和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? 如何使用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

I think rather than handling with two different tables, I will declare an unique index (constraint) spanning multiple columns, in you case if you think two items are equal if tuple (title, url) are equal, then declare a uniqueness constrain on both (title, url). 我认为不是处理两个不同的表,而是要声明一个跨越多个列的唯一索引(约束),如果您认为如果元组(标题,URL)相等,则两项是相等的,然后在两者上声明唯一性约束(标题,网址)。 You can simply insert values to your main table, and when you try to save a duplicate item, postgres will throw an exception, which is IntegrityException in SqlAlchemy. 您可以简单地将值插入到主表中,然后当您尝试保存重复项时,postgres将引发异常,即SqlAlchemy中的IntegrityException。 Catch that exception and ignore it. 捕获该异常并忽略它。 Something along the line of[3]. 沿着[3]的路线。

Please do remember that IntegrityException is kind of catch all. 请记住,IntegrityException非常有用。

Please see: 请参见:

[1] https://www.postgresql.org/docs/9.0/indexes-unique.html [1] https://www.postgresql.org/docs/9.0/indexes-unique.html

[2] https://docs.sqlalchemy.org/en/latest/core/constraints.html#unique-constraint [2] https://docs.sqlalchemy.org/zh-CN/latest/core/constraints.html#unique-constraint

[3] What is the good approach to check an existance of unique values in database table by SqlAlchemy in python2.7 [3] 在python2.7中通过SqlAlchemy检查数据库表中唯一值是否存在的好方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM