How connect to existing SQLite db for reading only

1,009 views
Skip to first unread message

Flx Files

unread,
May 7, 2018, 4:43:38 AM5/7/18
to peewee-orm
 
Hi all. I have a silly question.

This my code:

--------------------------------------------

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()
-------------------------------------------------------------------

This code is working fine, but if the file db don't exist, db.connect always create it.   How I can't prevent this ?

Another question is , How can query table database for this field without declare the peewee Model?

Thanks
 

Charles Leifer

unread,
May 7, 2018, 9:13:54 AM5/7/18
to peewe...@googlegroups.com
It's not a silly question -- the Python SQLite driver doesn't expose the flags parameter for the C function sqlite3_open_v2(), which would enable you to specify open read-only and/or create-if-not-exist. With the Python SQLite driver you always get SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE.

You can open read-only by using a URI. See https://docs.python.org/3/library/sqlite3.html#sqlite3.connect for details on using a URI.

For avoiding creating the db if it doesn't exist, you can use the os module:

db_filename = 'my-app.db'
if not os.path.exists(db_filename):
    print('db does not exist.')

--
You received this message because you are subscribed to the Google Groups "peewee-orm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to peewee-orm+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Flx Files

unread,
May 7, 2018, 11:17:49 AM5/7/18
to peewee-orm

Thanks Charles, your answers, as always, is very detailed.

I just wanted to make sure that there is is not another way in Peewee than check if file exist already.

Thanks

Reply all
Reply to author
Forward
0 new messages