gpt4 book ai didi

python - 如何在 Django 中下载 CSV 文件?

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:03 25 4
gpt4 key购买 nike

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

最佳答案

在您的 View 中导入 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

关于python - 如何在 Django 中下载 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com