Tuesday, October 17, 2023

Write code that uses django's settings.py file if django is installed

 

I'm writing a library file for django, and I want it to store settings in the settings.py file, which is django's default configuration location for settings. However, I still want the library to work if django isn't installed. Here's how I did it :

You can wrap an import statement in a try except block

This way, it doesn't crash if the reference doesn't exist

try:
    from django.conf import settings
except ImportError:
    pass

Test to see if the referenced object exists before using it in code

Research online said python doesn't have a direct way to check if the reference exists, so you can use a try / except block instead

try: settings
   except NameError: settings = None

Test to see if 'settings' is None

If settings exists, use the django settings.py file. Otherwise use a flat file

if settings != None:
   if not settings.configured:
      settings.configure()
      self._key_list = settings.MY_LIB_SETTINGS
   else:
      filename = "lib_api_config.txt"
      f = open(filename,"r")
      file_contents = f.read()
      f.close()
      self._key_list = json.loads(file_contents)

No comments: