如何在 Django 中下载 CSV 文件?

我为亚马逊产品抓取创建了一个小型 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")


呼如林
浏览 168回答 1
1回答

小怪兽爱吃肉

在您的视图中导入 csv 和 smart_str 包。使用以下代码以 CSV 格式下载数据。import csvfrom django.utils.encoding import smart_strdef 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python