如何在Django中下载CSV文件?

时间:2019-09-09 05:13:47

标签: python django beautifulsoup python-requests

我创建了一个用于亚马逊产品抓取的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")

1 个答案:

答案 0 :(得分: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