(sqlite)=
SQLite is a fast and lightweight SQL database engine that stores data either in memory or in a single file on disk.
Despite its simplicity, SQLite is a powerful tool. For example, it‘s the primary storage system for a number of common applications including Firefox, Chrome, and many components of both Android and iOS. It’s well suited for caching, and requires no extra configuration or dependencies, which is why it's used as the default backend for requests-cache.
SQLite will be used as the default backend without providing any arguments. If you want to pass extra connection options or just want to be explicit, initialize your session with a {py:class}.SQLiteCache instance:
>>> from requests_cache import CachedSession, SQLiteCache >>> backend = SQLiteCache() >>> session = CachedSession(backend=backend)
Or initialize it by alias:
>>> session = CachedSession(backend='sqlite')
This backend accepts any keyword arguments for {py:func}sqlite3.connect:
>>> backend = SQLiteCache(timeout=30)
http_cache.sqlite will be created in the current working directory.SQLiteCache.sqlite will be usedfiles for general info on specifying cache pathsExample
>>> backend = SQLiteCache('cache/http_cache.sqlite')
SQLite also supports in-memory databases. You can enable this (in “shared” memory mode) with the use_memory option:
>>> backend = SQLiteCache(use_memory=True)
Or specify a memory URI with additional options:
>>> backend = SQLiteCache(':file:memdb1?mode=memory')
Or just :memory:, if you are only using the cache from a single thread:
>>> backend = SQLiteCache(':memory:')
When working with average-sized HTTP responses (< 1MB) and using a modern SSD for file storage, you can expect speeds of around:
Of course, this will vary based on hardware specs, response size, and other factors.
The fast_save option can be used to increase cache write performance, but with the possibility of data loss. See pragma: synchronous <https://www.sqlite.org/pragma.html#pragma_synchronous>_ for details.
>>> backend = SQLiteCache(fast_save=True)
SQLite supports concurrent access, so it is safe to use from a multi-threaded and/or multi-process application. It supports unlimited concurrent reads. Writes, however, are queued and run in serial, so if you need to make large volumes of concurrent requests, you may want to consider a different backend that's specifically made for that kind of workload, like {py:class}.RedisCache.
One option to consider is Write Ahead Logging <https://sqlite.org/wal.html>_. This comes with a number of tradeoffs, but most notably it allows read operations to not block writes. This can be enabled with the wal option:
>>> backend = SQLiteCache(wal=True)
There are some caveats to using SQLite with some hosting services, based on what kind of storage is available:
sqlite3.OperationalError: database is locked.