|
1 | 1 | import csv
|
| 2 | +import io |
2 | 3 | import logging
|
3 | 4 | import ntpath
|
4 | 5 | import os
|
5 | 6 | from collections import OrderedDict
|
6 | 7 | from functools import partial
|
7 | 8 |
|
8 | 9 | from django.conf import settings
|
| 10 | +from django.core.files.storage import DefaultStorage |
9 | 11 | from django.core.management.base import CommandError
|
10 | 12 | from django.db.models import OuterRef
|
11 | 13 | from django.db.models import Subquery
|
|
26 | 28 | from kolibri.core.query import GroupConcatSubquery
|
27 | 29 | from kolibri.core.tasks.management.commands.base import AsyncCommand
|
28 | 30 | from kolibri.core.tasks.utils import get_current_job
|
29 |
| -from kolibri.core.utils.csv import open_csv_for_writing |
30 | 31 | from kolibri.core.utils.csv import output_mapper
|
31 | 32 | from kolibri.utils import conf
|
32 | 33 |
|
@@ -153,17 +154,20 @@ def translate_labels():
|
153 | 154 |
|
154 | 155 |
|
155 | 156 | 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)) |
158 | 162 | queryset = FacilityUser.objects.filter(facility=facility)
|
159 | 163 |
|
160 | 164 | header_labels = translate_labels().values()
|
161 | 165 |
|
162 |
| - csv_file = open_csv_for_writing(filepath) |
| 166 | + csv_file = io.BytesIO() |
163 | 167 |
|
164 | 168 | 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)) |
167 | 171 | writer.writeheader()
|
168 | 172 | usernames = set()
|
169 | 173 |
|
@@ -203,6 +207,17 @@ def csv_file_generator(facility, filepath, overwrite=True):
|
203 | 207 | usernames.add(item["username"])
|
204 | 208 | yield item
|
205 | 209 |
|
| 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 | + |
206 | 221 |
|
207 | 222 | class Command(AsyncCommand):
|
208 | 223 | def add_arguments(self, parser):
|
|
0 commit comments