我正在学习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)
3条答案
按热度按时间6jjcrrmo1#
您有一处打字错误,它是
exist_ok
,而不是exists_ok
。正确的代码应为:然而,这对您也不起作用,因为
exist_ok
是Python 3.2中添加的。您使用的是Python 2.7,但本书是为Python 3(可能是3.4,我不确定)编写的。在Python 2.7中,当目录已经存在时,你可以捕获异常:
但是,我强烈建议您改用Python 3,如果您试图用Python 2编写Python 3代码,您会遇到其他问题。
um6iljoc2#
在我的情况下(python 3.9作为QGIS 3.20.3的一部分,与OSGeo4W一起安装),错误是由文件夹中存在的两个pathlib.py文件引起的:
删除
C:\OSGeo4W\apps\Python39\Lib\site-packages
中的重复项后,问题得到解决。0yg35tkg3#
使用
python prototypes.py build
命令,它将由python 2运行