所以我要掌握Django,或者尝试。我有一些代码不依赖于网页调用 - 它旨在用信息填充数据库。最终它将被设置为一个过夜运行的cron作业。这是它的第一个破解,即做一个初始种群(一旦我有了这个工作,我将转移到一个添加结构,只有新记录被推送。)我正在使用Python 2.7,Django 1.5和Sqlite3 。当我运行此代码时,我得到了
Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
这似乎相当明显,但我现在花了几个小时试图找出如何调整设置。如何拨打/打开连接/这里有什么正确的术语?我有许多这样的功能,这将是预定的工作,这让我整个下午都感到沮丧。
import urllib2
import csv
import requests
from django.db import models
from gmbl.models import Match
master_data_file = urllib2.urlopen("http://www.football-data.co.uk/mmz4281/1213/E0.csv", "GET")
data = list(tuple(rec) for rec in csv.reader(master_data_file, delimiter=','))
for row in data:
current_match = Match(matchdate=row[1],
hometeam=row[2],
awayteam = row [3],
homegoals = row [4],
awaygoals = row[5],
homeshots = row[10],
awayshots = row[11],
homeshotsontarget = row[12],
awayshotsontarget = row[13],
homecorners = row[16],
awaycorners = row[17])
current_match.save()
我最初是从http://django-csv-importer.readthedocs.org/en/latest/开始的,但我遇到了同样的错误,并且文档尝试调试它没有多大意义。当我尝试在函数中调用settings.configure时,它说它不存在;大概我不得不导入它,但无法做到这一点。
答案 0 :(得分:1)
确保Django,你的项目在PYTHONPATH然后你可以做:
import urllib2
import csv
import requests
from django.core.management import setup_environ
from django.db import models
from yoursite import settings
setup_environ(settings)
from gmbl.models import Match
master_data_file = urllib2.urlopen("http://www.football-data.co.uk/mmz4281/1213/E0.csv", "GET")
data = list(tuple(rec) for rec in csv.reader(master_data_file, delimiter=','))
# ... your code ...
参考:http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
希望它有所帮助!