如何将CSV文件直接发送到FTP服务器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将CSV文件直接发送到FTP服务器相关的知识,希望对你有一定的参考价值。
我的问题是如何将CSV文件发送到FTP服务器。如您所见,以下脚本是我当前的代码:
代码示例:
def download_outage_info_all(request):
upload_data = download_data_form(request.POST)
if upload_data.is_valid():
print("valid")
start = upload_data.cleaned_data['start_date_time']
end = upload_data.cleaned_data['end_date_time']
print(start, '-', end)
start_timestamp = datetime.strptime(
start, '%Y-%m-%d %H:%M')
end_timestamp = datetime.strptime(
end, '%Y-%m-%d %H:%M')
try:
info = planned_outages.objects.filter(
start_timestamp__gte=start_timestamp, end_timestamp__lte=end_timestamp).values()
except Exception as e:
print("EXCEPTION", e)
print("**** Data not found *** ")
filename_date_part = datetime.now().strftime("%Y%m%d%H%M")
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename=m_availability_' +
filename_date_part + '.csv'
writer = csv.writer(response, delimiter=';')
writer.writerow(['starts YYYY-mm-dd HH:MM:SS', 'time_zone',
'ends YYYY-mm-dd HH:MM:SS', 'asset id', 'availability type', 'PowerKW'])
for x in info:
try:
unit_mw = unit_details.objects.get(
unit_id=x['unit_id_id'])
# prints to csv file
writer.writerow([x['start_timestamp'], 'UTC',
x['end_timestamp'], unit_mw.unit_name,x['availability_type'], x['capacity_kw']])
except Exception as e:
print("EXCEPTION", e)
print("**** Data not found for unit_mw*** ")
return response
这是一个Django视图,我不想在我的本地系统上保存CSV,我只是想直接将它发送到FTP服务器。谁能帮我?
答案
将CSV文件写入内存中类文件对象(例如BytesIO
)并上传:
from ftplib import FTP
from io import BytesIO
import csv
flo = BytesIO()
writer = csv.writer(flo, delimiter=';')
writer.writerow(...)
ftp = FTP('ftp.example.com')
ftp.login('username', 'password')
flo.seek(0)
ftp.storbinary('STOR test.csv', flo)
以上是关于如何将CSV文件直接发送到FTP服务器的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JavaScript 将 pdf 文件直接发送到打印机?
SpringAMQP RabbitMQ如何在没有Exchange的情况下直接发送到队列