52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
import os
|
|
import sys
|
|
|
|
# 添加项目根目录到Python路径
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
# 设置Django环境变量
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
|
|
|
|
# 初始化Django
|
|
import django
|
|
django.setup()
|
|
|
|
from crud_book.models import CrudBookModel
|
|
from django.core.files import File
|
|
import shutil
|
|
|
|
# 获取ID为2的图书
|
|
book = CrudBookModel.objects.filter(id=2).first()
|
|
|
|
if book:
|
|
print(f'当前图书信息: {book}')
|
|
|
|
# 源文件路径
|
|
source_file = 'booksdata/Hamlet/pg1524-images.epub'
|
|
source_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), source_file)
|
|
|
|
# 检查源文件是否存在
|
|
if os.path.exists(source_path):
|
|
print(f'找到源文件: {source_path}')
|
|
|
|
# 目标路径
|
|
media_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'media')
|
|
books_dir = os.path.join(media_root, 'books')
|
|
os.makedirs(books_dir, exist_ok=True)
|
|
|
|
# 复制文件到媒体目录
|
|
target_filename = 'hamlet.epub'
|
|
target_path = os.path.join(books_dir, target_filename)
|
|
shutil.copy2(source_path, target_path)
|
|
print(f'文件已复制到: {target_path}')
|
|
|
|
# 更新图书的file字段
|
|
with open(target_path, 'rb') as f:
|
|
book.file.save(target_filename, File(f), save=True)
|
|
|
|
print(f'图书文件已更新: {book.file.url}')
|
|
print(f'文件路径: {book.file.path}')
|
|
else:
|
|
print(f'源文件不存在: {source_path}')
|
|
else:
|
|
print('未找到ID为2的图书') |