Skip to content

Commit

Permalink
break out util
Browse files Browse the repository at this point in the history
  • Loading branch information
villebro committed Feb 8, 2022
1 parent 23c8524 commit ee93f12
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 10 deletions.
16 changes: 6 additions & 10 deletions superset/charts/data/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@

import json
import logging
from io import BytesIO
from typing import Any, Dict, Optional, TYPE_CHECKING
from zipfile import ZipFile

import simplejson
from flask import current_app, g, make_response, request, Response
Expand All @@ -46,7 +44,7 @@
from superset.exceptions import QueryObjectValidationError
from superset.extensions import event_logger
from superset.utils.async_query_manager import AsyncQueryTokenException
from superset.utils.core import json_int_dttm_ser
from superset.utils.core import create_zip, json_int_dttm_ser
from superset.views.base import CsvResponse, generate_download_headers
from superset.views.base_api import statsd_metrics

Expand Down Expand Up @@ -357,14 +355,12 @@ def _send_chart_response(
else:
# return multi-query csv results bundled as a zip file
encoding = current_app.config["CSV_EXPORT"].get("encoding", "utf-8")
buf = BytesIO()
with ZipFile(buf, "w") as bundle:
for idx, result in enumerate(result["queries"]):
with bundle.open(f"query_{idx + 1}.csv", "w") as fp:
fp.write(result["data"].encode(encoding))
buf.seek(0)
files = {
f"query_{idx + 1}.csv": result["data"].encode(encoding)
for idx, result in enumerate(result["queries"])
}
return Response(
buf,
create_zip(files),
headers=generate_download_headers("zip"),
mimetype="application/zip",
)
Expand Down
12 changes: 12 additions & 0 deletions superset/utils/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from email.mime.text import MIMEText
from email.utils import formatdate
from enum import Enum, IntEnum
from io import BytesIO
from timeit import default_timer
from types import TracebackType
from typing import (
Expand All @@ -61,6 +62,7 @@
Union,
)
from urllib.parse import unquote_plus
from zipfile import ZipFile

import bleach
import markdown as md
Expand Down Expand Up @@ -1788,3 +1790,13 @@ def apply_max_row_limit(limit: int, max_limit: Optional[int] = None,) -> int:
if limit != 0:
return min(max_limit, limit)
return max_limit


def create_zip(files: Dict[str, Any]) -> BytesIO:
buf = BytesIO()
with ZipFile(buf, "w") as bundle:
for filename, contents in files.items():
with bundle.open(filename, "w") as fp:
fp.write(contents)
buf.seek(0)
return buf
20 changes: 20 additions & 0 deletions tests/integration_tests/charts/data/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@
import unittest
import copy
from datetime import datetime
from io import BytesIO
from typing import Optional
from unittest import mock
from zipfile import ZipFile

from flask import Response
from tests.integration_tests.conftest import with_feature_flags
from superset.models.sql_lab import Query
Expand Down Expand Up @@ -243,6 +246,22 @@ def test_with_csv_result_format(self):
self.query_context_payload["result_format"] = "csv"
rv = self.post_assert_metric(CHART_DATA_URI, self.query_context_payload, "data")
assert rv.status_code == 200
assert rv.mimetype == "text/csv"

@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_with_multi_query_csv_result_format(self):
"""
Chart data API: Test chart data with multi-query CSV result format
"""
self.query_context_payload["result_format"] = "csv"
self.query_context_payload["queries"].append(
self.query_context_payload["queries"][0]
)
rv = self.post_assert_metric(CHART_DATA_URI, self.query_context_payload, "data")
assert rv.status_code == 200
assert rv.mimetype == "application/zip"
zipfile = ZipFile(BytesIO(rv.data), "r")
assert zipfile.namelist() == ["query_1.csv", "query_2.csv"]

@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_with_csv_result_format_when_actor_not_permitted_for_csv__403(self):
Expand Down Expand Up @@ -766,6 +785,7 @@ def test_chart_data_get(self):
}
)
rv = self.get_assert_metric(f"api/v1/chart/{chart.id}/data/", "get_data")
assert rv.mimetype == "application/json"
data = json.loads(rv.data.decode("utf-8"))
assert data["result"][0]["status"] == "success"
assert data["result"][0]["rowcount"] == 2
Expand Down

0 comments on commit ee93f12

Please sign in to comment.