Skip to main content
 首页 » 编程设计

python之如何在没有相对项目路径的子目录中使用 Django 设置运行脚本

2024年08月26日30zdz8207

我想执行位于 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' 

目录树:

|___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() 

请您参考如下方法:

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

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

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