亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號