【问题标题】:SqlAlchemy 'datetime.datetime' is not mappedSqlAlchemy 'datetime.datetime' 未映射
【发布时间】:2020-06-15 09:23:14
【问题描述】:

我正在使用 Scrapy 通过 Whois 模块获取域及其创建日期。然后我使用 SqlAlchemy 将它们添加到 MySQL 数据库,但是在将创建日期添加到数据库时出现以下错误,因为数据类型是 <class 'datetime.datetime'>

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'datetime.datetime' is not mapped

我尝试将日期转换为字符串,但随后出现另一个错误。

pipelines.py:

class SaveDomainsPipeline(object):
    def __init__(self):
        engine = db_connect()
        create_table(engine)
        self.Session = sessionmaker(bind=engine)


    def process_item(self, item, spider):
        session = self.Session()
        domain = Domains(**item)
        domain_item = item['domain']
        domain_whois = whois.query(domain_item)
        creation_date = domain_whois.creation_date


        try:
            session.add_all([domain, creation_date])
            session.commit()

models.py

class Domains(Base):
    __tablename__ = "domains"

    id = Column(Integer, primary_key=True)
    date_added = Column(DateTime(timezone=True), server_default=func.now())
    domain = Column('domain', Text())
    creation_date = Column('creation_date', DateTime(timezone=True))
    #creation_date = Column('creation_date', Text()) -- I also tried this

【问题讨论】:

  • 为什么要在会话中添加creation_date
  • 添加域创建日期和域

标签: python-3.x sqlalchemy scrapy


【解决方案1】:

我在原始代码中犯了一个菜鸟错误。 当我启动“域”类的一个实例时,我必须在填充我最初错过的列时引用它。工作代码如下。

class SaveDomainsPipeline(object):
    def __init__(self):
        engine = db_connect()
        create_table(engine)
        self.Session = sessionmaker(bind=engine)


    def process_item(self, item, spider):
        session = self.Session()
        domains = Domains() #initiate instance of Domains class.
        domains.domain = item['domain'] #Add the item "domain" from Items to DB
        domain_whois = whois.query(domains.domain)
        domains.creation_date = domain_whois.creation_date #Add the creation date to DB

        try:
            #save the instance which saves both the domain item and creation date.
            session.add(domains) 

            session.commit()

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2013-06-20
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2018-01-14
    相关资源
    最近更新 更多