簡體   English   中英

如何將 CSV 文件直接發送到 FTP 服務器

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

我的問題是如何將 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 服務器。 還將 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