Skip to content

Commit 43309bc

Browse files
committed
WIP - Users CSV export use DefaultStorage
1 parent 793b83f commit 43309bc

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

kolibri/core/auth/management/commands/bulkexportusers.py

+21-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import csv
2+
import io
23
import logging
34
import ntpath
45
import os
56
from collections import OrderedDict
67
from functools import partial
78

89
from django.conf import settings
10+
from django.core.files.storage import DefaultStorage
911
from django.core.management.base import CommandError
1012
from django.db.models import OuterRef
1113
from django.db.models import Subquery
@@ -26,7 +28,6 @@
2628
from kolibri.core.query import GroupConcatSubquery
2729
from kolibri.core.tasks.management.commands.base import AsyncCommand
2830
from kolibri.core.tasks.utils import get_current_job
29-
from kolibri.core.utils.csv import open_csv_for_writing
3031
from kolibri.core.utils.csv import output_mapper
3132
from kolibri.utils import conf
3233

@@ -153,17 +154,20 @@ def translate_labels():
153154

154155

155156
def csv_file_generator(facility, filepath, overwrite=True):
156-
if not overwrite and os.path.exists(filepath):
157-
raise ValueError("{} already exists".format(filepath))
157+
file_storage = DefaultStorage()
158+
filename = file_storage.generate_filename(filepath.split("/")[-1])
159+
160+
if not overwrite and file_storage.exists(filename):
161+
raise ValueError("{} already exists".format(filename))
158162
queryset = FacilityUser.objects.filter(facility=facility)
159163

160164
header_labels = translate_labels().values()
161165

162-
csv_file = open_csv_for_writing(filepath)
166+
csv_file = io.BytesIO()
163167

164168
with csv_file as f:
165-
writer = csv.DictWriter(f, header_labels)
166-
logger.info("Creating csv file {filename}".format(filename=filepath))
169+
writer = csv.DictWriter(io.TextIOWrapper(f, encoding="utf-8"), header_labels)
170+
logger.info("Creating users csv file {filename}".format(filename=filepath))
167171
writer.writeheader()
168172
usernames = set()
169173

@@ -203,6 +207,17 @@ def csv_file_generator(facility, filepath, overwrite=True):
203207
usernames.add(item["username"])
204208
yield item
205209

210+
f.seek(0)
211+
file = file_storage.save(filename, f)
212+
213+
try:
214+
# If the file is local, we can get the path
215+
logger.info("File saved - Path: {}".format(file_storage.path(file)))
216+
except NotImplementedError:
217+
# But if path is not implemented, we assume we can get the URL
218+
logger.info("File saved - Path: {}".format(file_storage.url(file)))
219+
logger.info("File saved - Size: {}".format(file_storage.size(file)))
220+
206221

207222
class Command(AsyncCommand):
208223
def add_arguments(self, parser):

0 commit comments

Comments
 (0)