runtime
484 / 500
question 484 Application Delivery · medium

Read a .env file

In development, settings live in a .env file instead of the real environment. Read one into a dictionary the settings loader (L04) can use, rejecting lines that would silently set the wrong thing.

Functionread_dotenv(text)
LinesKEY=value; blank lines and lines starting with # are skipped; spaces around the key and the value are removed
Keysmust fully match [A-Z_][A-Z0-9_]*
Quotesa value wrapped in matching "…" or '…' has them removed (the inside is kept as-is); otherwise the value is used as written
Repeatsa key set twice keeps the later value
RaisesValueError naming the line number (from 1) for a line without = or with an invalid key
Examples
callread_dotenv('# local development\nAPP_ENV=dev\nDATABASE_URL=sqlite:///market.db?mode=rwc\nGREETING="Welcome to Runtime Market"\n')returns{'APP_ENV': 'dev', 'DATABASE_URL': 'sqlite:///market.db?mode=rwc', 'GREETING': 'Welcome to Runtime Market'}
callread_dotenv('PORT = 8000\n\n')returns{'PORT': '8000'}
callread_dotenv("NOTE='it''s fine'\n")returns{'NOTE': "it''s fine"}

Loading your progress…

Read a .env file — Python practice · Runtime