python
49 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
import csv
from django.http import StreamingHttpResponse, FileResponse
class Echo:
"""Helper for writing to streaming response."""
def write(self, value):
return value
def export_large_csv(request):
"""Stream large CSV without loading all data in memory."""
def generate_rows():
"""Generator yielding CSV rows."""
from products.models import Product
# Yield header
yield ['ID', 'Name', 'Price', 'Stock']
# Stream products in chunks
for product in Product.objects.iterator(chunk_size=1000):
yield [
str(product.id),
product.name,
str(product.price),
str(product.stock)
]
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
rows = (writer.writerow(row) for row in generate_rows())
response = StreamingHttpResponse(
rows,
content_type='text/csv'
)
response['Content-Disposition'] = 'attachment; filename="products.csv"'
return response
def download_file(request, file_path):
"""Serve file download efficiently."""
response = FileResponse(
open(file_path, 'rb'),
content_type='application/octet-stream'
)
response['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"'
return response
1 file · python
Explain with highlit
Streaming responses serve large files without loading them entirely into memory. I use StreamingHttpResponse or FileResponse for file downloads. For CSV generation, I yield rows incrementally. The generator pattern keeps memory usage constant regardless of file size. I set appropriate content-type and content-disposition headers. For video streaming, I implement range request support. This enables serving large datasets or media files efficiently without server memory limits.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
ruby
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
rails
performance
streaming
by codesnips
3 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem
class DashboardView(TemplateView):
Django aggregation with annotate for statistics
django
python
database
by Priya Sharma
1 tab
Share this code
Here's the card — post it anywhere.