Anas Baheh
Anas Baheh

Reputation: 137

import variables if file exists

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

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

Upvotes: 0

Views: 419

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

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

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

Upvotes: 1

Anas Baheh
Anas Baheh

Reputation: 137

I had to add the main directory name to access it

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

Upvotes: 0

Related Questions