【问题标题】:How to run script with Django settings in subdirectory without relative project path如何在没有相对项目路径的子目录中使用 Django 设置运行脚本
【发布时间】:2015-04-16 19:36:46
【问题描述】:

我想执行位于restaurants_project/scripts/seeds.py 脚本。这个种子文件将使用我的 Django 模型Restaurant,根据同一文件夹中的 CSV 数据,将餐厅记录填充到我的数据库中。我发现包含项目设置(即restaurant_project.settings)以及我必要的模型的唯一方法是在种子文件中添加sys.path.append('MY_PROJECTS_RELATIVE_PATH')。我显然不想在生产中这样做(或者我不想这样做?)所以在不获得以下ImportError 的情况下包含这些设置的最佳方法是什么:

ImportError: Could not import settings 'restaurants_project.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named 'restaurants_project'

Directory Tree:

|___restaurants_project
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| | |____settings.cpython-34.pyc
| |____settings.py
| |____urls.py
| |____wsgi.py
|____restaurants
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| | |____admin.cpython-34.pyc
| | |____models.cpython-34.pyc
| |____admin.py
| |____migrations
| | |______init__.py
| |____models.py
| |____tests.py
| |____views.py
|____scripts
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| |____restaurant_inspections_2014.csv
| |____seeds.py
| |____unique_restaurant_ids.txt

seeds.py:

import os, sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'restaurants_project.settings')

import django
django.setup()

import csv
csvfile = open('restaurant_inspections_2014.csv')
reader = csv.reader(csvfile)
headers = next(reader, None)

for row in reader:
  print(row)
  import pdb; pdb.set_trace()

【问题讨论】:

    标签: python django python-3.x django-models


    【解决方案1】:

    编写使用项目设置的脚本的最佳方法是编写自定义管理命令:

    https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/

    基本上,您应该将脚本包装在扩展 BaseCommand 的类中,并将其放在应用程序的 management/commands 目录中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      相关资源
      最近更新 更多