betodealmeida commented on code in PR #35478:
URL: https://github.com/apache/superset/pull/35478#discussion_r2429843961


##########
superset/charts/data/api.py:
##########
@@ -462,3 +496,116 @@ def _create_query_context_from_form(
             return ChartDataQueryContextSchema().load(form_data)
         except KeyError as ex:
             raise ValidationError("Request is incorrect") from ex
+
+    def _should_use_streaming(
+        self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
+    ) -> bool:
+        """Determine if streaming should be used based on actual row count 
threshold."""
+        from flask import current_app as app
+
+        query_context = result["query_context"]
+        result_format = query_context.result_format
+
+        # Only support CSV streaming currently
+        if result_format.lower() != "csv":
+            return False
+
+        # Get streaming threshold from config
+        threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)
+
+        # Extract actual row count (same logic as frontend)
+        actual_row_count = None

Review Comment:
   ```suggestion
           actual_row_count: int | None = None
   ```



##########
superset/charts/data/api.py:
##########
@@ -462,3 +496,116 @@ def _create_query_context_from_form(
             return ChartDataQueryContextSchema().load(form_data)
         except KeyError as ex:
             raise ValidationError("Request is incorrect") from ex
+
+    def _should_use_streaming(
+        self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
+    ) -> bool:
+        """Determine if streaming should be used based on actual row count 
threshold."""
+        from flask import current_app as app
+
+        query_context = result["query_context"]
+        result_format = query_context.result_format
+
+        # Only support CSV streaming currently
+        if result_format.lower() != "csv":
+            return False
+
+        # Get streaming threshold from config
+        threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)
+
+        # Extract actual row count (same logic as frontend)
+        actual_row_count = None
+        viz_type = form_data.get("viz_type") if form_data else None
+
+        # For table viz, try to get actual row count from query results
+        if viz_type == "table" and result.get("queries"):
+            # Check if we have rowcount in the second query result (like 
frontend does)
+            queries = result.get("queries", [])
+            if len(queries) > 1 and queries[1].get("data"):
+                data = queries[1]["data"]
+                if isinstance(data, list) and len(data) > 0:
+                    actual_row_count = data[0].get("rowcount")
+
+        # Fallback to row_limit if actual count not available
+        if actual_row_count is None:
+            if form_data and "row_limit" in form_data:
+                actual_row_count = form_data.get("row_limit", 0)
+            elif query_context.form_data and "row_limit" in 
query_context.form_data:
+                actual_row_count = query_context.form_data.get("row_limit", 0)
+
+        # Use streaming if row count meets or exceeds threshold
+        if actual_row_count is not None and actual_row_count >= threshold:
+            return True
+
+        return False
+
+    def _create_streaming_csv_response(
+        self,
+        result: dict[Any, Any],
+        form_data: dict[str, Any] | None = None,
+        filename: str | None = None,
+        expected_rows: int | None = None,
+    ) -> Response:
+        """Create a streaming CSV response for large datasets."""
+        from datetime import datetime
+
+        from flask import Response

Review Comment:
   Same here, move these to top-level.



##########
superset/charts/data/api.py:
##########
@@ -462,3 +496,116 @@ def _create_query_context_from_form(
             return ChartDataQueryContextSchema().load(form_data)
         except KeyError as ex:
             raise ValidationError("Request is incorrect") from ex
+
+    def _should_use_streaming(
+        self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
+    ) -> bool:
+        """Determine if streaming should be used based on actual row count 
threshold."""
+        from flask import current_app as app
+
+        query_context = result["query_context"]
+        result_format = query_context.result_format
+
+        # Only support CSV streaming currently
+        if result_format.lower() != "csv":
+            return False
+
+        # Get streaming threshold from config
+        threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)
+
+        # Extract actual row count (same logic as frontend)
+        actual_row_count = None
+        viz_type = form_data.get("viz_type") if form_data else None
+
+        # For table viz, try to get actual row count from query results
+        if viz_type == "table" and result.get("queries"):
+            # Check if we have rowcount in the second query result (like 
frontend does)
+            queries = result.get("queries", [])
+            if len(queries) > 1 and queries[1].get("data"):
+                data = queries[1]["data"]
+                if isinstance(data, list) and len(data) > 0:
+                    actual_row_count = data[0].get("rowcount")
+
+        # Fallback to row_limit if actual count not available
+        if actual_row_count is None:
+            if form_data and "row_limit" in form_data:
+                actual_row_count = form_data.get("row_limit", 0)
+            elif query_context.form_data and "row_limit" in 
query_context.form_data:
+                actual_row_count = query_context.form_data.get("row_limit", 0)
+
+        # Use streaming if row count meets or exceeds threshold
+        if actual_row_count is not None and actual_row_count >= threshold:
+            return True
+
+        return False
+
+    def _create_streaming_csv_response(
+        self,
+        result: dict[Any, Any],
+        form_data: dict[str, Any] | None = None,
+        filename: str | None = None,
+        expected_rows: int | None = None,
+    ) -> Response:
+        """Create a streaming CSV response for large datasets."""
+        from datetime import datetime
+
+        from flask import Response
+
+        from superset.commands.chart.data.streaming_export_command import (
+            StreamingCSVExportCommand,
+        )

Review Comment:
   And move this to top-level if possible (no circular imports).



##########
superset/charts/data/api.py:
##########
@@ -462,3 +496,116 @@ def _create_query_context_from_form(
             return ChartDataQueryContextSchema().load(form_data)
         except KeyError as ex:
             raise ValidationError("Request is incorrect") from ex
+
+    def _should_use_streaming(
+        self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
+    ) -> bool:
+        """Determine if streaming should be used based on actual row count 
threshold."""
+        from flask import current_app as app
+
+        query_context = result["query_context"]
+        result_format = query_context.result_format
+
+        # Only support CSV streaming currently
+        if result_format.lower() != "csv":
+            return False
+
+        # Get streaming threshold from config
+        threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)
+
+        # Extract actual row count (same logic as frontend)
+        actual_row_count = None
+        viz_type = form_data.get("viz_type") if form_data else None
+
+        # For table viz, try to get actual row count from query results
+        if viz_type == "table" and result.get("queries"):
+            # Check if we have rowcount in the second query result (like 
frontend does)
+            queries = result.get("queries", [])
+            if len(queries) > 1 and queries[1].get("data"):
+                data = queries[1]["data"]
+                if isinstance(data, list) and len(data) > 0:
+                    actual_row_count = data[0].get("rowcount")
+
+        # Fallback to row_limit if actual count not available
+        if actual_row_count is None:
+            if form_data and "row_limit" in form_data:
+                actual_row_count = form_data.get("row_limit", 0)
+            elif query_context.form_data and "row_limit" in 
query_context.form_data:
+                actual_row_count = query_context.form_data.get("row_limit", 0)
+
+        # Use streaming if row count meets or exceeds threshold
+        if actual_row_count is not None and actual_row_count >= threshold:
+            return True
+
+        return False
+
+    def _create_streaming_csv_response(
+        self,
+        result: dict[Any, Any],
+        form_data: dict[str, Any] | None = None,
+        filename: str | None = None,
+        expected_rows: int | None = None,
+    ) -> Response:
+        """Create a streaming CSV response for large datasets."""
+        from datetime import datetime
+
+        from flask import Response
+
+        from superset.commands.chart.data.streaming_export_command import (
+            StreamingCSVExportCommand,
+        )
+
+        query_context = result["query_context"]
+
+        # Use filename from frontend if provided, otherwise generate one
+        if not filename:
+            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+            chart_name = "export"
+
+            if form_data and form_data.get("slice_name"):
+                chart_name = form_data["slice_name"]
+            elif form_data and form_data.get("viz_type"):
+                chart_name = form_data["viz_type"]
+
+            # Sanitize chart name for filename
+            safe_chart_name = "".join(
+                c for c in chart_name if c.isalnum() or c in ("-", "_")
+            )
+            filename = f"superset_{safe_chart_name}_{timestamp}.csv"
+
+        logger.info(
+            "Creating streaming CSV response: %s (from frontend: %s)",
+            filename,
+            filename is not None,
+        )
+        if expected_rows:
+            logger.info("Using expected_rows from frontend: %d", expected_rows)
+
+        # Execute streaming command
+        chunk_size = 1000
+        command = StreamingCSVExportCommand(query_context, chunk_size)
+        command.validate()
+
+        # Get the callable that returns the generator
+        csv_generator_callable = command.run()
+
+        # Get encoding from config
+        encoding = app.config.get("CSV_EXPORT", {}).get("encoding", "utf-8")
+
+        # Create response with streaming headers
+        response = Response(
+            csv_generator_callable(),  # Call the callable to get generator
+            mimetype=f"text/csv; charset={encoding}",
+            headers={
+                "Content-Disposition": f'attachment; filename="{filename}"',
+                "Cache-Control": "no-cache",
+                "X-Accel-Buffering": "no",  # Disable nginx buffering
+                "X-Superset-Streaming": "true",  # Identify streaming responses

Review Comment:
   Do we need this custom header? I assume Flask is setting `Transfer-Encoding: 
chunked` in the response, can we use that instead? (or add it, if not present)



##########
superset/commands/sql_lab/streaming_export_command.py:
##########
@@ -0,0 +1,239 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command for streaming CSV exports of SQL Lab query results."""
+
+from __future__ import annotations
+
+import csv
+import io
+import logging
+import time
+from typing import Callable, Generator, TYPE_CHECKING
+
+from flask import current_app as app
+from flask_babel import gettext as __
+
+from superset import db
+from superset.commands.base import BaseCommand
+from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
+from superset.exceptions import SupersetErrorException, 
SupersetSecurityException
+from superset.models.sql_lab import Query
+from superset.sql.parse import SQLScript
+from superset.sqllab.limiting_factor import LimitingFactor
+
+if TYPE_CHECKING:
+    pass

Review Comment:
   +1



##########
superset/charts/data/api.py:
##########
@@ -462,3 +496,116 @@ def _create_query_context_from_form(
             return ChartDataQueryContextSchema().load(form_data)
         except KeyError as ex:
             raise ValidationError("Request is incorrect") from ex
+
+    def _should_use_streaming(
+        self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
+    ) -> bool:
+        """Determine if streaming should be used based on actual row count 
threshold."""
+        from flask import current_app as app
+
+        query_context = result["query_context"]
+        result_format = query_context.result_format
+
+        # Only support CSV streaming currently
+        if result_format.lower() != "csv":
+            return False
+
+        # Get streaming threshold from config
+        threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)
+
+        # Extract actual row count (same logic as frontend)
+        actual_row_count = None
+        viz_type = form_data.get("viz_type") if form_data else None
+
+        # For table viz, try to get actual row count from query results
+        if viz_type == "table" and result.get("queries"):
+            # Check if we have rowcount in the second query result (like 
frontend does)
+            queries = result.get("queries", [])
+            if len(queries) > 1 and queries[1].get("data"):
+                data = queries[1]["data"]
+                if isinstance(data, list) and len(data) > 0:
+                    actual_row_count = data[0].get("rowcount")
+
+        # Fallback to row_limit if actual count not available
+        if actual_row_count is None:
+            if form_data and "row_limit" in form_data:
+                actual_row_count = form_data.get("row_limit", 0)
+            elif query_context.form_data and "row_limit" in 
query_context.form_data:
+                actual_row_count = query_context.form_data.get("row_limit", 0)
+
+        # Use streaming if row count meets or exceeds threshold
+        if actual_row_count is not None and actual_row_count >= threshold:
+            return True
+
+        return False
+
+    def _create_streaming_csv_response(
+        self,
+        result: dict[Any, Any],
+        form_data: dict[str, Any] | None = None,
+        filename: str | None = None,
+        expected_rows: int | None = None,
+    ) -> Response:
+        """Create a streaming CSV response for large datasets."""
+        from datetime import datetime
+
+        from flask import Response
+
+        from superset.commands.chart.data.streaming_export_command import (
+            StreamingCSVExportCommand,
+        )
+
+        query_context = result["query_context"]
+
+        # Use filename from frontend if provided, otherwise generate one
+        if not filename:
+            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+            chart_name = "export"
+
+            if form_data and form_data.get("slice_name"):
+                chart_name = form_data["slice_name"]
+            elif form_data and form_data.get("viz_type"):
+                chart_name = form_data["viz_type"]
+
+            # Sanitize chart name for filename
+            safe_chart_name = "".join(
+                c for c in chart_name if c.isalnum() or c in ("-", "_")
+            )
+            filename = f"superset_{safe_chart_name}_{timestamp}.csv"

Review Comment:
   It's better to use `secure_filename` from `werkzeug`.



##########
superset/commands/chart/data/streaming_export_command.py:
##########
@@ -0,0 +1,176 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command for streaming CSV exports of large datasets."""
+
+from __future__ import annotations
+
+import csv
+import io
+import logging
+import time
+from typing import Callable, Generator, TYPE_CHECKING
+
+from flask import current_app as app
+
+from superset.commands.base import BaseCommand
+
+if TYPE_CHECKING:
+    from superset.common.query_context import QueryContext
+
+logger = logging.getLogger(__name__)
+
+
+class StreamingCSVExportCommand(BaseCommand):
+    """
+    Command to execute a streaming CSV export.
+
+    This command handles the business logic for:
+    - Executing database queries with server-side cursors
+    - Generating CSV data in chunks
+    - Managing database connections
+    - Buffering data for efficient streaming
+    """
+
+    def __init__(
+        self,
+        query_context: QueryContext,
+        chunk_size: int = 1000,
+    ):
+        """
+        Initialize the streaming export command.
+
+        Args:
+            query_context: The query context containing datasource and query 
details
+            chunk_size: Number of rows to fetch per database query (default: 
1000)
+        """
+        self._query_context = query_context
+        self._chunk_size = chunk_size
+        self._current_app = app._get_current_object()
+
+    def validate(self) -> None:
+        """Validate permissions and query context."""
+        self._query_context.raise_for_access()
+
+    def run(self) -> Callable[[], Generator[str, None, None]]:  # noqa: C901
+        """
+        Execute the streaming CSV export.
+
+        Returns:
+            A callable that returns a generator yielding CSV data chunks as 
strings.
+            The callable is needed to maintain Flask app context during 
streaming.
+        """
+
+        def csv_generator() -> Generator[str, None, None]:  # noqa: C901
+            """Generator that yields CSV data from database query."""
+            with self._current_app.app_context():
+                start_time = time.time()
+                total_bytes = 0
+
+                try:
+                    from superset import db
+                    from superset.connectors.sqla.models import SqlaTable
+
+                    datasource = self._query_context.datasource
+
+                    with db.session() as session:
+                        if isinstance(datasource, SqlaTable):
+                            datasource = session.merge(datasource)
+
+                        query_obj = self._query_context.queries[0]
+                        sql_query = 
datasource.get_query_str(query_obj.to_dict())
+
+                        with datasource.database.get_sqla_engine() as engine:
+                            connection = engine.connect()
+
+                            try:
+                                from sqlalchemy import text

Review Comment:
   This is a lot of nesting; it would be better to refactor this method and 
split it into multiple methods to avoid so many nesting levels.
   
   Also, this import can be on the top-level.



##########
superset/commands/chart/data/streaming_export_command.py:
##########
@@ -0,0 +1,176 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command for streaming CSV exports of large datasets."""
+
+from __future__ import annotations
+
+import csv
+import io
+import logging
+import time
+from typing import Callable, Generator, TYPE_CHECKING
+
+from flask import current_app as app
+
+from superset.commands.base import BaseCommand
+
+if TYPE_CHECKING:
+    from superset.common.query_context import QueryContext
+
+logger = logging.getLogger(__name__)
+
+
+class StreamingCSVExportCommand(BaseCommand):
+    """
+    Command to execute a streaming CSV export.
+
+    This command handles the business logic for:
+    - Executing database queries with server-side cursors
+    - Generating CSV data in chunks
+    - Managing database connections
+    - Buffering data for efficient streaming
+    """
+
+    def __init__(
+        self,
+        query_context: QueryContext,
+        chunk_size: int = 1000,
+    ):
+        """
+        Initialize the streaming export command.
+
+        Args:
+            query_context: The query context containing datasource and query 
details
+            chunk_size: Number of rows to fetch per database query (default: 
1000)
+        """
+        self._query_context = query_context
+        self._chunk_size = chunk_size
+        self._current_app = app._get_current_object()
+
+    def validate(self) -> None:
+        """Validate permissions and query context."""
+        self._query_context.raise_for_access()
+
+    def run(self) -> Callable[[], Generator[str, None, None]]:  # noqa: C901
+        """
+        Execute the streaming CSV export.
+
+        Returns:
+            A callable that returns a generator yielding CSV data chunks as 
strings.
+            The callable is needed to maintain Flask app context during 
streaming.
+        """
+
+        def csv_generator() -> Generator[str, None, None]:  # noqa: C901
+            """Generator that yields CSV data from database query."""
+            with self._current_app.app_context():
+                start_time = time.time()
+                total_bytes = 0
+
+                try:
+                    from superset import db
+                    from superset.connectors.sqla.models import SqlaTable
+
+                    datasource = self._query_context.datasource
+
+                    with db.session() as session:
+                        if isinstance(datasource, SqlaTable):
+                            datasource = session.merge(datasource)
+
+                        query_obj = self._query_context.queries[0]
+                        sql_query = 
datasource.get_query_str(query_obj.to_dict())
+
+                        with datasource.database.get_sqla_engine() as engine:
+                            connection = engine.connect()
+
+                            try:
+                                from sqlalchemy import text
+
+                                result_proxy = connection.execution_options(
+                                    stream_results=True
+                                ).execute(text(sql_query))
+
+                                columns = list(result_proxy.keys())
+
+                                # Use StringIO with csv.writer for proper 
escaping
+                                buffer = io.StringIO()
+                                csv_writer = csv.writer(
+                                    buffer, quoting=csv.QUOTE_MINIMAL
+                                )
+
+                                # Write CSV header
+                                csv_writer.writerow(columns)
+                                header_data = buffer.getvalue()
+                                total_bytes += len(header_data.encode("utf-8"))
+                                yield header_data
+                                buffer.seek(0)
+                                buffer.truncate()
+
+                                row_count = 0
+                                flush_threshold = 65536  # 64KB
+
+                                while True:
+                                    rows = 
result_proxy.fetchmany(self._chunk_size)
+                                    if not rows:
+                                        break

Review Comment:
   You can simply do:
   
   ```python
   while rows := result_proxy.fetchmany(self._chunk_size):
       ...
   ```



##########
superset/charts/data/api.py:
##########
@@ -462,3 +496,116 @@ def _create_query_context_from_form(
             return ChartDataQueryContextSchema().load(form_data)
         except KeyError as ex:
             raise ValidationError("Request is incorrect") from ex
+
+    def _should_use_streaming(
+        self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
+    ) -> bool:
+        """Determine if streaming should be used based on actual row count 
threshold."""
+        from flask import current_app as app

Review Comment:
   You should be able to have this at the top of the file.



##########
superset/sqllab/api.py:
##########
@@ -294,6 +294,130 @@ def export_csv(self, client_id: str) -> CsvResponse:
         )
         return response
 
+    @expose("/export_streaming/", methods=("POST",))
+    @protect()
+    @permission_name("read")
+    @statsd_metrics
+    @event_logger.log_this_with_context(
+        action=lambda self,
+        *args,
+        **kwargs: f"{self.__class__.__name__}.export_streaming_csv",
+        log_to_statsd=False,
+    )
+    def export_streaming_csv(self) -> Response:
+        """Export SQL query results using streaming for large datasets.
+        ---
+        post:
+          summary: Export SQL query results to CSV with streaming
+          requestBody:
+            description: Export parameters
+            required: true
+            content:
+              application/x-www-form-urlencoded:
+                schema:
+                  type: object
+                  properties:
+                    client_id:
+                      type: string
+                      description: The SQL query result identifier
+                    filename:
+                      type: string
+                      description: Optional filename for the export
+                    expected_rows:
+                      type: integer
+                      description: Optional expected row count for progress 
tracking
+          responses:
+            200:
+              description: Streaming CSV export
+              content:
+                text/csv:
+                  schema:
+                    type: string
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            403:
+              $ref: '#/components/responses/403'
+            404:
+              $ref: '#/components/responses/404'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        # Extract parameters from form data
+        client_id = request.form.get("client_id")
+        filename = request.form.get("filename")
+
+        if not client_id:
+            return self.response_400(message="client_id is required")
+
+        expected_rows = None
+        if expected_rows_str := request.form.get("expected_rows"):
+            try:
+                expected_rows = int(expected_rows_str)
+            except (ValueError, TypeError):
+                logger.warning("Invalid expected_rows value: %s", 
expected_rows_str)
+
+        return self._create_streaming_csv_response(client_id, filename, 
expected_rows)
+
+    def _create_streaming_csv_response(
+        self,
+        client_id: str,
+        filename: str | None = None,
+        expected_rows: int | None = None,
+    ) -> Response:
+        """Create a streaming CSV response for large SQL Lab result sets."""
+        from datetime import datetime
+
+        from superset.commands.sql_lab.streaming_export_command import (
+            StreamingSqlResultExportCommand,
+        )
+
+        # Execute streaming command
+        chunk_size = 1000
+        command = StreamingSqlResultExportCommand(client_id, chunk_size)
+        command.validate()
+
+        # Generate filename if not provided
+        if not filename:
+            query = command._query
+            assert query is not None
+            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+            safe_name = "".join(
+                c for c in (query.name or "query") if c.isalnum() or c in 
("-", "_")
+            )
+            filename = f"sqllab_{safe_name}_{timestamp}.csv"
+
+        # Get the callable that returns the generator
+        csv_generator_callable = command.run()
+
+        # Get encoding from config
+        encoding = app.config.get("CSV_EXPORT", {}).get("encoding", "utf-8")
+
+        # Create response with streaming headers
+        response = Response(
+            csv_generator_callable(),  # Call the callable to get generator
+            mimetype=f"text/csv; charset={encoding}",
+            headers={
+                "Content-Disposition": f'attachment; filename="{filename}"',
+                "Cache-Control": "no-cache",
+                "X-Accel-Buffering": "no",  # Disable nginx buffering
+                "X-Superset-Streaming": "true",  # Identify streaming responses

Review Comment:
   Same question here about using a standard header.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to