Exemple #1
0
    def csv_export(self, data):
        delimiters = {
            "newline": "\n",
            "comma": ", ",
        }
        delimiter = delimiters[self.cleaned_data.get("data_delimiter")]

        for row in data:
            for key, value in row.items():
                if isinstance(value, list):
                    row[key] = delimiter.join(value)

        output = StringIO()
        writer = csv.DictWriter(output, fieldnames=data[0].keys())
        writer.writeheader()
        writer.writerows(data)
        content = output.getvalue()
        return HttpResponse(
            content,
            content_type="text/plain",
            headers={
                "Content-Disposition": f'attachment; filename="{self.filename}.csv"',
                "Access-Control-Allow-Origin": "*",
            },
        )
Exemple #2
0
 def render(self, **kwargs):
     fieldnames, data = self.get_data()
     output = StringIO()
     writer = csv.DictWriter(output, fieldnames=fieldnames)
     writer.writeheader()
     writer.writerows(data)
     content = output.getvalue()
     return self.filename, "text/plain", content
def write_failed_download_manifest(failed_list: List[Dict[str, str]]) -> None:
    logger.warning("Writing failed download ids to file: %s",
                   FAILED_DOWNLOAD_FILENAME)

    fieldnames = ["case_id", "file_id", "reason"]
    with open(FAILED_DOWNLOAD_FILENAME, "a") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter="\t")
        # Only write the headers if there's nothing in the file yet.
        if os.stat(FAILED_DOWNLOAD_FILENAME).st_size == 0:
            writer.writeheader()
        writer.writerows(failed_list)
Exemple #4
0
def test_dictwriter():
    f = StringIO()
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(f, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({
        'first_name': 'Lovely',
        'last_name': '@SUM(1+1)*cmd|\' /C calc\'!A0 '
    })
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

    f.seek(0)
    assert f.read() == "first_name,last_name\r\nBaked,Beans\r\n" \
                       "Lovely,'@SUM(1+1)*cmd\\|' /C calc'!A0 \r\nWonderful,Spam\r\n"