Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Django Standalone Script - Import by filename is not supported

Tags:

python

django

I have the following script and it's meant to be a standalone Django script so I can run python my_script.py from the command line. It used to work with Django 1.8, after I upgrade to Django 1.11, I'm getting the following error:

Traceback (most recent call last):
  File "app.py", line 8, in <module>
    django.setup()
  File "C:\python27\lib\site-packages\django-1.11.5-py2.7.egg\django\__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\python27\lib\site-packages\django-1.11.5-py2.7.egg\django\conf\__init__.py", line 56, in __getattr__
    self._setup(name)
  File "C:\python27\lib\site-packages\django-1.11.5-py2.7.egg\django\conf\__init__.py", line 41, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\python27\lib\site-packages\django-1.11.5-py2.7.egg\django\conf\__init__.py", line 110, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\python27\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
ImportError: Import by filename is not supported.

This is my python script

# standalone django setup
import os, sys, logging, django
prj_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
logging.basicConfig(level=logging.INFO)
logging.info("PRJ_DIR: %s" % prj_dir)
sys.path.append(prj_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "%s.settings" % prj_dir.split("/")[-1])
django.setup()

...
...
like image 728
user1187968 Avatar asked Dec 13 '22 20:12

user1187968


2 Answers

It seems you're trying to split a file path by the forward slash / while running your script on Windows where path separator is the backslash \. Use os.path.basename instead of manually dealing with the stings (.split("/")[-1]):

>>> import os
>>> os.path.basename(r'/home/user/project')
'project'
>>> os.path.basename(r'c:\users\user\project')
'project'

In comparison:

>>> r'/home/user/project'.split("/")[-1]
'project'  # works
>>> r'c:\users\user\project'.split("/")[-1]
'c:\\users\\user\\project'  # error
like image 157
Igonato Avatar answered Dec 16 '22 10:12

Igonato


Don't reinvent the wheel. There is a cool manage command on django extensions that lets you run scripts on the django context.

https://django-extensions.readthedocs.io/en/latest/runscript.html

like image 20
Julio Avatar answered Dec 16 '22 10:12

Julio