简体   繁体   English

如何将 CSV 文件直接发送到 FTP 服务器

[英]How to send CSV file directly to an FTP server

My question is How can I send a CSV file to an FTP server.我的问题是如何将 CSV 文件发送到 FTP 服务器。 As you can see, the following script is the current code of mine:如您所见,以下脚本是我的当前代码:

Code sample:代码示例:

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

This is a Django view, I don't want to save the CSV on my local system, I just want to directly send it to an FTP server.这是一个 Django 视图,我不想将 CSV 保存在本地系统上,我只想将其直接发送到 FTP 服务器。 Can anyone help me?谁能帮我?

Write the CSV file to an in-memory file-like object (eg BytesIO ) and upload that:将 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)

So my this seems to work for me in sending a CSV file to an FTP server.所以我的这似乎适用于我将 CSV 文件发送到 FTP 服务器。 Also incorporating the schedule library created by Dan Bader to running the script as a scheduled task on the client side.还将 Dan Bader 创建的计划库合并到在客户端将脚本作为计划任务运行。

from ftplib import FTP
import schedule
import time


FTP_HOST = "192.168.0.101"
FTP_PORT = 7021
FTP_USER = "username"
FTP_PASS = "password"



def job():
    print("I'm working...")
    ftp = FTP()
    ftp.connect(FTP_HOST, FTP_PORT)
    ftp.login(FTP_USER, FTP_PASS)


    # local file name you want to upload
    filename = "madison_office_2020.csv"
    with open(filename, "rb") as file:
        # use FTP's STOR command to upload the file
        ftp.storbinary(f"STOR {filename}", file)

    ftp.quit()


#schedule.every(30).seconds.do(job)
#schedule.every(10).minutes.do(job)
#schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
#schedule.every(5).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("13:15").do(job)
#schedule.every().minute.at(":17").do(job)


while True:
    schedule.run_pending()
    time.sleep(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM