外部Python脚本和Django虚拟环境

时间:2020-11-11 17:06:23

标签: python django django-rest-framework django-views virtualenv

我以这种方式通过子进程从Django应用运行外部脚本:

class ExecutePythonFileView(View):
    def get(self, request):
        # Execute script
        script_path = os.path.join(settings.BASE_DIR, '/Code/zenet/zenet/workers/stats_scraper.py')
        subprocess.call(['python', script_path])
        # Return response
        return HttpResponse("Executed!")

我需要通过Django虚拟环境执行它,我该如何进行?

1 个答案:

答案 0 :(得分:1)

您有两种选择,

选项1:

  • 将脚本升级为管理命令
  • 使用django.core.management.call_command运行脚本
  • 这样,如果需要,Django会负责产生子流程及其相关内容

选项2:

  • 使用相同的方法
  • 如下更新视图
import sys

class ExecutePythonFileView(View):
    def get(self, request):
        # Execute script
        script_path = os.path.join(settings.BASE_DIR, '/Code/zenet/zenet/workers/stats_scraper.py')
        subprocess.call([sys.executable, script_path])
        # Return response
        return HttpResponse("Executed!")