【问题标题】:How to download CSV file in Django?如何在 Django 中下载 CSV 文件?
【发布时间】:2020-01-10 21:02:26
【问题描述】:

我为亚马逊产品抓取创建了一个小型 Django 项目。但不知道如何下载 CSV 文件。

我是这方面的初学者,所以我不知道如何给出下载链接,所以我没有尝试任何东西

import csv
import re

import requests
from bs4 import BeautifulSoup

from django.http import HttpResponse
from django.shortcuts import render


def index(request):

    url = request.POST.get("url", "")
    r = requests.get(url)
    soup = BeautifulSoup(r.content, features="lxml")
    p_name = soup.find_all("h2", attrs={"class": "a-size-mini"})
    p_price = soup.find_all("span", attrs={"class": "a-price-whole"})

    with open("product_file.csv", mode="w") as product_file:
        product_writer = csv.writer(product_file)
        for name, price in zip(p_name, p_price):
            product_writer.writerow([name.text, price.text])

    return render(request, "index.html")

【问题讨论】:

    标签: python django beautifulsoup python-requests


    【解决方案1】:

    在您的视图中导入 csv 和 smart_str 包。使用以下代码以 CSV 格式下载数据。

    import csv
    from django.utils.encoding import smart_str
    
    def download_csv_data(request):
       # response content type
       response = HttpResponse(content_type='text/csv')
    
       #decide the file name
       response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.csv"'
    
       writer = csv.writer(response, csv.excel)
       response.write(u'\ufeff'.encode('utf8'))
    
       #write the headers
       writer.writerow([
         smart_str(u"Event Name"),
         smart_str(u"Start Date"),
         smart_str(u"End Date"),
         smart_str(u"Notes"),
       ])
    
       #get data from database or from text file....
       events = event_services.get_events_by_year(year) #dummy function to fetch data
       for event in events:
         writer.writerow([
            smart_str(event.name),
            smart_str(event.start_date_time),
            smart_str(event.end_date_time),
            smart_str(event.notes),
         ])
       return response
    

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 2021-08-25
      • 2021-01-05
      • 2012-12-06
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多