我正在运行一个转换脚本,该脚本使用 Django 的 ORM 将大量数据提交到数据库。我使用手动提交来加速这个过程。我有数百个文件要提交,每个文件将创建超过一百万个对象。
我使用的是 Windows 7 64 位。我注意到 Python 进程一直在增长,直到消耗超过 800MB,而这只是第一个文件!
脚本循环遍历文本文件中的记录,重复使用相同的变量并且不累积任何列表或元组。
我读了here这是 Python(也许是任何程序)的普遍问题,但我希望 Django 或 Python 有一些明确的方法来减少进程大小......
下面是代码的概述:
import sys,os
sys.path.append(r'D:\MyProject')
os.environ['DJANGO_SETTINGS_MODULE']='my_project.settings'
from django.core.management import setup_environ
from convert_to_db import settings
from convert_to_db.convert.models import Model1, Model2, Model3
setup_environ(settings)
from django.db import transaction
@transaction.commit_manually
def process_file(filename):
data_file = open(filename,'r')
model1, created = Model1.objects.get_or_create([some condition])
if created:
option.save()
while 1:
line = data_file.readline()
if line == '':
break
if not(input_row_i%5000):
transaction.commit()
line = line[:-1] # remove \n
elements = line.split(',')
d0 = elements[0]
d1 = elements[1]
d2 = elements[2]
model2, created = Model2.objects.get_or_create([some condition])
if created:
option.save()
model3 = Model3(d0=d0, d1=d1, d2=d2)
model3 .save()
data_file.close()
transaction.commit()
# Some code that calls process_file() per file
最佳答案
首先,确保 settings.py 中的 DEBUG=False
。当 DEBUG=True
时,发送到数据库的所有查询都存储在 django.db.connection.queries
中。如果您导入许多记录,这将变成大量内存。您可以通过 shell 检查它:
$ ./manage.py shell
> from django.conf import settings
> settings.DEBUG
True
> settings.DEBUG=False
> # django.db.connection.queries will now remain empty / []
如果这没有帮助,那么尝试产生一个新的 Process为每个文件运行 process_file。这不是最有效的,但您正试图降低内存使用率而不是 CPU 周期。像这样的事情应该让你开始:
from multiprocessing import Process
for filename in files_to_process:
p = Process(target=process_file, args=(filename,))
p.start()
p.join()
关于Python进程在django db上传脚本中不断增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4292963/