Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put standalone-django scripts without breaking imports?

Tags:

python

django

I'm still pretty new to Python.

I have a Django website with several apps and a /libs directory. I need to add a couple cron jobs that will use my Django models. I've already worked all that out, no big deal.

I have a problem with my imports, though.

I would like to include these scripts in the App they generally belong-to. But when I execute the script from the commandline, it's unable to load modules from the /libs directory.

To illustrate specifically the dir structure, imagine this pseudo-code:

import ./../libs/mysharedlib.py   

In other words the scripts and sharedlib are:

~/project/myapp/myscript.py

~/project/libs/mysharedlib.py

I get that I could just add ~/project to my PYTHONPATH but then I have to worry about doing this during deployment and it just feels broken.

Should I move my scripts out of my apps and put them in the ~/project? Is there a better way?

like image 605
Shane H Avatar asked Aug 18 '12 15:08

Shane H


People also ask

What is admin py in Django?

django-admin.py is Django's command-line utility for administrative tasks. This document outlines all it can do. In addition, manage.py is automatically created in each Django project.


1 Answers

There is a better way, custom management commands solve this. https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

These let you write stand alone utility scripts. You can run these as a cron or just as utilities. They use the exact same paths as any other module in your django app.

While these solve import problems does your libs directory have a __init__.py file? Can you import your lib directory in your views? Or is your import just not working in your cron scripts? Either way custom managment commands address this.

like image 135
dm03514 Avatar answered Sep 28 '22 00:09

dm03514