简体   繁体   English

如何从Django项目外的脚本运行Django Shell命令

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

I have a web scraper. 我有一个网页刮板。 It outputs JSON data. 它输出JSON数据。 I have a Django project that uses this JSON data. 我有一个使用此JSON数据的Django项目。 These are in two separate repos/directories. 这些位于两个单独的存储库/目录中。

My scraper copies the data file into my Django project. 我的抓取工具将数据文件复制到Django项目中。 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? 如何使我的scraper脚本(再次位于Django项目之外)运行命令?

(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.) (谷歌搜索这些搜索词给了我一个反面的问题,问如何从命令行运行python脚本。我想从python脚本运行命令提示符。)

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 . 使用这个答案

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. 您还可以通过使脚本将GET请求发送到特定的URL来非常简单地实现此目的,并且可以将Django中的URL映射到特定的视图。 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. 对于UNIX系统,您可以简单地使用CURL,而且我敢肯定,在Windows中也是如此,您必须进行一些搜索。

I needed to activate the virtual environment for my shell command to work. 我需要激活虚拟环境以使Shell命令正常工作。 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: 另外,/ home / [我的名字] /。virtualenvs / [项目目录] / bin / activate是不可执行的,为了使脚本正常工作,我必须使其变为可执行的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM