def measure_version_file_download(topic_slug, subtopic_slug, measure_slug, version, filename): try: *_, measure_version = page_service.get_measure_version_hierarchy( topic_slug, subtopic_slug, measure_slug, version) upload_obj = upload_service.get_upload(measure_version, filename) downloaded_file = upload_service.get_measure_download( upload_obj, filename, "source") content = get_csv_data_for_download(downloaded_file) if os.path.exists(downloaded_file): os.remove(downloaded_file) if content.strip() == "": abort(404) outfile = NamedTemporaryFile("w", encoding="windows-1252", delete=False) outfile.write(content) outfile.flush() return send_file(outfile.name, as_attachment=True, mimetype="text/csv", attachment_filename=filename) except (UploadNotFoundException, FileNotFoundError, ClientError): abort(404)
def test_only_adds_quotes_to_non_quoted_values(): csv_with_embedded_quotes = "./tests/test_data/csv_with_embedded_quotes.csv" csv_with_quotes = '"Ethnicity","Value","Description"\n"Black","10","Test"\n"White","12.2","This is a ""test"""\n' assert get_csv_data_for_download( csv_with_embedded_quotes) == csv_with_quotes
def test_adds_quotes(): directory = os.path.abspath(os.path.dirname(__file__)) csv_with_no_quotes = os.path.join(directory, "test_data/csv_with_no_quotes.csv") csv_with_quotes = '"Ethnicity","Value"\n"Black","10"\n"White","12.2"\n' assert get_csv_data_for_download(csv_with_no_quotes) == csv_with_quotes
def test_only_adds_quotes_to_non_quoted_values(): directory = os.path.abspath(os.path.dirname(__file__)) csv_with_embedded_quotes = os.path.join( directory, "test_data/csv_with_embedded_quotes.csv") csv_with_quotes = '"Ethnicity","Value","Description"\n"Black","10","Test"\n"White","12.2","This is a ""test"""\n' assert get_csv_data_for_download( csv_with_embedded_quotes) == csv_with_quotes
def write_measure_version_downloads(measure_version, slug): if measure_version.uploads: download_dir = os.path.join(slug, "downloads") os.makedirs(download_dir, exist_ok=True) for d in measure_version.uploads: try: filename = upload_service.get_measure_download(d, d.file_name, "source") content = get_csv_data_for_download(filename) file_path = os.path.join(download_dir, d.file_name) with open(file_path, "w", encoding="windows-1252") as download_file: download_file.write(content) except Exception as e: message = "Error writing download for file %s" % d.file_name print(message) print(e)
def test_adds_quotes(): csv_with_no_quotes = "./tests/test_data/csv_with_no_quotes.csv" csv_with_quotes = '"Ethnicity","Value"\n"Black","10"\n"White","12.2"\n' assert get_csv_data_for_download(csv_with_no_quotes) == csv_with_quotes