从模块导入类是否在导入时执行整个模块? python 3

时间:2020-11-06 19:28:43

标签: python sqlite module sqlalchemy

我在一个名为schema.py的文件中创建了一个数据库和2个表模式:

import sqlalchemy as sql
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class ProjGutIndex(Base):
    __tablename__ = 'Project Gutenberg Index'

    id = sql.Column(sql.Integer, primary_key=True)
    title = sql.Column(sql.String)
    link = sql.Column(sql.String)
    description = sql.Column(sql.Text)

    def __repr__(self):
        return "id\t%s | title\t%s | description\t%s" %(self.id, self.title, self.description)

engine = sql.create_engine('sqlite:///../docs/database.db', echo=True)
Base.metadata.create_all(engine)

,然后我想通读文件并提交到该表。但是据我了解,我需要导入该表类(ProjGutIndex)才能执行类似(db_load.py)的操作:

import sqlalchemy as sql
from sqlalchemy.orm import sessionmaker
import os
from bs4 import BeautifulSoup
import re
from schema import ProjGutIndex

file_wd = os.path.dirname(os.path.realpath(__file__))
relative_path = '/PG_catalogue/PG_catalogue_2020-11-04/cache/epub'
abs_path = file_wd + relative_path
indices = os.listdir(abs_path)

engine = sql.create_engine('sqlite:///../docs/database.db', echo=True)
Session = sessionmaker(bind=engine)

...

session = Session()
        
listed = session.query(ProjGutIndex).filter(ProjGutIndex.title.like(book_title)).first()

if not listed:
    book = ProjGutIndex(title=book_title.strip(), description=book_description.strip()+' '+str(book_cover).strip())
    session.add(book)
    session.commit()
else:
    with open(file_wd+'/../docs/importlog.txt', 'a+') as log:
        f.write(index+' EXISTS,\n')
        
session.close()
...

运行此代码时,我的代码失败并显示:

...
sqlite3.OperationalError: unable to open database file

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "e:/.../myapplication/db_load.py", line 6, in <module>
    from schema import ProjGutIndex
  File "e:\...\myapplication\schema.py", line 29, in <module>
    Base.metadata.create_all(engine)
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file
(Background on this error at: http://sqlalche.me/e/13/e3q8)

文件夹结构为:

myapplication/
---- db_load.py
---- schema.py
docs/
---- logfiles.txt
---- database.db

我想知道:

  1. 如果我只是从该模块导入一个类,为什么它在Base.metadata.create_all(engine)行上有问题。为什么还要运行?
  2. 每次我从脚本中导入内容时,整个脚本(schema.py)是否都会运行?
  3. 如果要导入该类以在db_load.py中使用它,现在如何解决此问题?
  4. 在哪里可以阅读有关申请的归档惯例的信息?我不知道文件夹的结构方式是否愚蠢。

1 个答案:

答案 0 :(得分:1)

从另一个文件导入时,它将运行整个文件。如果您不想运行文件的一部分,则将其放在if __name__ == "__main__"中,如下所示:

if __name__ == "__main__":
    engine = sql.create_engine('sqlite:///../docs/database.db', echo=True)
    Base.metadata.create_all(engine)