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.
Function
read_dotenv(text)Lines
KEY=value; blank lines and lines starting with # are skipped; spaces around the key and the value are removedKeysmust 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 writtenRepeatsa key set twice keeps the later value
Raises
ValueError naming the line number (from 1) for a line without = or with an invalid keyExamples
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"}