Danny
Danny

Reputation: 510

How to run a Django shell command from a script outside the Django project

I have a web scraper. It outputs JSON data. I have a Django project that uses this JSON data. These are in two separate repos/directories.

My scraper copies the data file into my Django project. What I want is for that scraper script to then run my custom command, which I would usually activate in the command line with:

python manage.py load_concerts name_of_file.json

How do I make my scraper script (which again, is outside of the Django project) run the commands?

(Googling these search terms is giving me people asking the opposite question, asking how to run a python script from the command line. I want to run a command prompt from a python script.)

Upvotes: 0

Views: 2671

Answers (3)

Rick Graves
Rick Graves

Reputation: 607

I needed to activate the virtual environment for my shell command to work. Here is the script that worked for me:

cd /home/[my name]/Devel/[project dir]
source /home/[my name]/.virtualenvs/[project dir]/bin/activate
python manage.py shell --command="from [somewhere] import [something]; [something]()"

Also /home/[my name]/.virtualenvs/[project dir]/bin/activate was not executable, I had to make it executable for the script to work:

chmod 755 /home/[my name]/.virtualenvs/[project dir]/bin/activate

Upvotes: 1

cyphx
cyphx

Reputation: 130

You can also achieve this very simply by making your script send a GET request to a particular URL and you can map the URL in Django to a particular view. Now you can do whatever it is that you want to do in that view function.

For UNIX systems you can simply use CURL and I'm sure it's fairly easy to do so in windows too, you'd have to search around a little bit.

Upvotes: 1

keepAlive
keepAlive

Reputation: 6655

What about doing

project_path = r'<path to where manage.py is>'
project_name = '<project name>'

import os
os.chdir(project_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", f"{project_name}.settings") #python3.6's best string formatting practice

from collections import OrderedDict
from django.apps import apps
from django.conf import settings
from django.core import management

apps.app_configs = OrderedDict()
apps.ready       = False
apps.populate(settings.INSTALLED_APPS)
management.call_command('load_concerts name_of_file.json')


using this answer.

Upvotes: 1

Related Questions