Home > OS >  import variables if file exists
import variables if file exists

Time:10-08

I have two Python files on the same level in my Django app.

  • settings.py
  • SECRET.py

I want to import the variables from SECRET.py in case the file exists.

# This code checks if you have the SECRET.py file to connect to the live server
if Path("SECRET.py").is_file():
    print("Live Database")
    from .SECRET import *
else:
    print("Local Database")
    NAME = 'blog_db'
    USER = 'postgres'
    PASSWORD = 'admin'
    HOST = 'localhost'
    PORT = '5432'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': NAME,
        'USER': USER,
        'PASSWORD': PASSWORD,
        'HOST': HOST,
        'PORT': PORT,
    }

}

The code keeps connecting to the local database; prints "Local Database", even though I have the SECRET.py file

CodePudding user response:

I had to add the main directory name to access it

if Path("myBlog/SECRET.py").is_file():

CodePudding user response:

You could also wrap it inside a try..except block

try:
  from .SECRET import *
except ImportError as error:
  # Do something else
  • Related