我正在使用“Lightweight Django”这本书学习Django。我正在使用Django 1.8。但是,我无法运行此代码。以下是错误消息:
工作树:
build.py
import os
import shutil
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from django.test.client import Client
def get_pages():
for name in os.listdir(settings.SITE_PAGES_DIRECTORY):
if name.endswith('.html'):
yield name[:-5]
class Command(BaseCommand):
help = 'Build static site output.'
leave_locale_alone = True
def handle(self, *args, **options):
if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
os.makedirs(settings.STATIC_ROOT, exists_ok=True)
call_command('collectstatic', interactive=False, clear=True,verbosity=0)
client = Client()
for page in get_pages():
url = reverse('page', kwargs={'slug': page})
response = client.get(url)
if page == 'index':
output_dir = settings.SITE_OUTPUT_DIRECTORY
else:
output_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)
os.makedirs(output_dir)
with open(os.path.join(output_dir, 'index.html'), 'wb') as f:
f.write(response.content)
prototypes.py
import os
import sys
from django.conf import settings
BASE_DIR = os.path.dirname(__file__)
settings.configure(
DEBUG = True,
SECRET_KEY= 'qfzf!b1z^5dyk%syiokeg4*2xf%kj68g=o&e8qvd@@(1lj5z8)',
ROOT_URLCONF='sitebuilder.urls',
MIDDLEWARE_CLASSES=(),
INSTALLED_APPS=(
'django.contrib.staticfiles',
'sitebuilder',
),
TEMPLATES=(
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[],
'APP_DIRS':True,
},
),
STATIC_URL='/static/',
SITE_PAGES_DIRECTORY=os.path.join(BASE_DIR,'pages'),
SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,'_build'),
STATIC_ROOT=os.path.join(BASE_DIR,'_build','static'),
)
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
答案 0 :(得分:13)
你有一个拼写错误,它是exist_ok
,而不是exists_ok
正确的代码应该是:
os.makedirs(settings.STATIC_ROOT, exist_ok=True)
但是,这对你也不起作用,因为在Python 3.2中添加了exist_ok
。您正在使用Python 2.7,但本书是为Python 3编写的(可能是3.4,我不确定)
在Python 2.7中,您可以在目录已存在时捕获异常:
try:
os.makedirs(settings.STATIC_ROOT)
except OSError as e:
if e.errno != errno.EEXIST:
raise
但是,我强烈建议您切换到Python 3.如果您尝试在Python 2中编写Python 3代码,则会遇到其他问题。