PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to load API keys from .env file successfully

 August 21, 2022     dotenv, environment-variables, python, python-3.x, syntax     No comments   

Issue

I have been referring to tutorials on the web, but something keeps on going wrong even though I follow them exactly.

I am trying to hide some API keys inside .env file, this is the content of my .env(same directory as init.py):

CONNSTRING = DefaultEndpointsProtocol=samplesamplesameplsamplesample

and this is inside my init.py

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
print(os.getenv("CONNSTRING"))

which does not work? not sure about the error, this is what it says:

System.Private.CoreLib: Result: Failure  
Exception: ModuleNotFoundError: No module named '__main__'

if usecwd or _is_interactive() or getattr(sys, 'frozen', False):
  File "D:\\\", line 265, in _is_interactive
    main = __import__('__main__', None, None, fromlist=['__file__'])

Solution

By default the .env should be at the same level as the file you execute. But you can specify a path as parameter of the load_dotenv method. Maybe you should try to get rid of the find_dotenv method and directly give the absolute path of your .env like so:

import os                                                                                                                                                                                                          
from dotenv import load_dotenv, find_dotenv
from pathlib import Path
load_dotenv(Path("/my/path/.env"))
print(os.getenv("CONNSTRING"))


Answered By - Martin Tovmassian
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing