使用 peewee 如何连接到现有的 SQLite 数据库以进行只读

With peewee how connect to existing SQLite db for reading only

我有一个愚蠢的问题。

这是我的代码:

  from peewee import *

   db = SqliteDatabase(None)

   class Base(Model):
       class Meta:
           database = db

   class Table(Base):
       a_date = DateField()
       url = CharField()

   def __main()__
       parser = argparse.ArgumentParser()
       parser.add_argument('--db-dir', action='store')
       args = parser.parse_args()
       db_path = os.path.join(args.db_dir, 'data.db')
       try:
           db.init(db_path)
           db.connect()
           query = Table.select().order_by(Table.a_date.desc()).get()   
       except Exception:
           sys.exit(1)
       else:
           print(query.url)

       sys.exit(0)


   if __name__ == '__main__':
       main()

此代码运行良好,但如果文件 db 不存在 db.connect 总是创建它。我该如何预防?

另一个问题是,如何在不声明 peewee 模型的情况下为该字段查询 table 数据库?

谢谢

如果我理解正确,peewee 文档 (http://docs.peewee-orm.com/en/latest/peewee/database.html),他们使用 python 提供的 api 来连接到 sqlite。

这意味着你必须处理这个 api (https://docs.python.org/2/library/sqlite3.html#sqlite3.connect),并且连接方法总是预先创建数据库。

但是我相信您可以将自定义连接 class 传递给此方法(参数工厂),您可以在此自定义 class.

中定义您的行为
import os

from sqlite3 import Connection
from peewee import *

class CustomConnection(Connection):
    def __init__(self, dbname, *args, **kwargs):
        # Check if db already exists or not
        if not os.path.exists(dbname):
            raise ValueError('DB {} does not exist'.format(dbname))
        super(CustomConnection, self).__init__(dbname, *args, **kwargs)

db = SqliteDatabase('mydatabase', factory=CustomConnection)