带断点续传能力的有状态数据迁移命令
实现一个可中断重启的management command,处理百万级数据时保存进度。 · 难度:入门 · +10XP
可恢复的数据迭代器
数据处理命令常因超时或错误中断,本教程教你构建一个支持断点续传的迭代器。利用文件或数据库记录当前处理到的主键ID(或偏移量),每次重启时从该位置继续。不仅支持单线程,还通过Redis队列实现分布式续传。你将学会如何自定义BaseCommand的handle方法,以及如何注册SIGTERM信号保存状态。
import os
import json
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
state_file = '/tmp/progress.json'
start_id = 0
if os.path.exists(state_file):
with open(state_file) as f:
start_id = json.load(f).get('last_id', 0)
queryset = MyModel.objects.filter(id__gt=start_id).order_by('id')
for instance in queryset.iterator():
# 处理数据
with open(state_file, 'w') as f:
json.dump({'last_id': instance.id}, f)