AskReference
CauseIntermediate

Why does data/creature.py import conn and curs from .init instead of importing sqlite3 directly?

The shared data/init.py module centralizes SQLite connection setup so that data/creature.py does not hardwire its own database connection. It gives creature.py access to a single conn and curs pair, can be reused for other data modules like explorer.py, and supports configuration through the CRYPTID_SQLITE_DB environment variable.

The original approach in Example 10-2 imported sqlite3 directly in data/creature.py and created conn and curs at the module level. The text then identifies a configuration problem: this hardwires database information in the code and leaves the initialization function uncalled, so there is no usable connection or cursor when other functions run. The solution was to create data/init.py, a separate initialization module, and have data modules import the shared conn and curs objects from it. This keeps the Web and Service layers unaware of Data layer internals, avoids duplicating connection code for both creature and explorer data, and lets the database name come from an external source, such as the CRYPTID_SQLITE_DB environment variable, with a default fallback. Additionally, because a Python module is a singleton, the initialization code in data/init.py runs only once even if it is imported by multiple data modules.

Key points

  • The initial data/creature.py code imported sqlite3 directly and created its own conn and curs, hardwiring the database.
  • The book says this leaves no initialized conn or curs because init() is never called, creating a configuration problem.
  • data/init.py was created to centralize SQLite initialization so creature.py and explorer.py can share one setup.
  • Using .init keeps database details inside the Data layer and supports an environment variable, CRYPTID_SQLITE_DB, for configuration and testing.
  • Because modules are singletons, importing data/init.py runs the setup only once.
Source:FastAPI: Modern Python Web Development· Data Layer· p. 142–160

Related questions

Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook