为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Django 中下载 CSV 文件?

如何在 Django 中下载 CSV 文件?

呼如林 2022-05-24 13:20:02
我为亚马逊产品抓取创建了一个小型 Django 项目。但不知道如何下载 CSV 文件。我是这方面的初学者,所以我不知道如何提供下载链接,所以我没有尝试过任何东西import csvimport reimport requestsfrom bs4 import BeautifulSoupfrom django.http import HttpResponsefrom django.shortcuts import renderdef 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 回答

?
小怪兽爱吃肉

TA贡献1852条经验 获得超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


查看完整回答
反对 回复 2022-05-24
  • 1 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号