Group Abstract Group Abstract

Message Boards Message Boards

0
|
21 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

How do I load secrets from a .env file?

Posted 12 hours ago

Question

How do I load variables from a .env file in Wolfram Language?

Storing secrets and configuration in a .env file is a widely adopted industry convention (popularised by the twelve-factor app methodology). Most languages have first-class support for it. In Python, this is commonly done like so:

from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("MY_API_KEY")

Given a standard .env file like:

# example .env file
STRIPE_API_KEY=scr_12345
TWILIO_API_KEY=abcd1234

what is a clean and idiomatic way to load these variables from a .env file in Wolfram Langauge?

This functionality could be a nice addition to the function repository.

See also: https://www.dotenv.org/docs/security/env.html

POSTED BY: Conor Cosnett
2 Replies

Since it looks like your file format is just lines of varName = varValue, you can just import as text, select the lines that have an =, and store the variable names and values as pairs:

text = Import["pathToYourFile.env", "Text"];
nameValuePairs = 
  Select[StringSplit[text, "\n"], StringContainsQ[#, "="] &];
nameValuePairs = StringSplit[#, "="] & /@ nameValuePairs
(*{{STRIPE_API_KEY,scr_12345},{TWILIO_API_KEY,abcd1234"}}*)

There's probably an even nicer way to do this with StringCases

POSTED BY: David Trimas

Have you tried (or seen) GetEnvironment[]?

I guess it doesn't read an external file, though, but just reports on the current environment. Looking around more, I guess it's not going to be helpful.

POSTED BY: Michael Rogers
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard