简体   繁体   中英

Python - create txt file on the fly and send it via FTP?

So i am currently creating a text file from a jinja2 template on the fly and having it be downloaded by the users browser, however i want to add an option to send it somewhere via FTP (all the FTP details are predefined and wont change) how do i create the file to be sent?

Thanks

code:

...
device_config.stream(
    STR         = hostname,
    IP          = subnet,
    BGPASNO     = bgp_as,
    LOIP        = lo1,
    DSLUSER     = dsl_user,
    DSLPASS     = dsl_pass,   
    Date        = install_date,
).dump(config_file)

content = config_file.getvalue()
content_type = 'text/plain'
content_disposition = 'attachment; filename=%s' % (file_name)

response = None

if type == 'FILE':
    response = HttpResponse(content, content_type=content_type)
    response['Content-Disposition'] = content_disposition    
elif type == 'FTP':
    with tempfile.NamedTemporaryFile() as temp:
        temp.write(content)
        temp.seek(0)
        filename = temp.name
        session = ftplib.FTP('192.168.1.1','test','password')
        session.storbinary('STOR {0}'.format(file_name), temp)
        session.quit()
        temp.flush()

return response

EDIT

needed to add temp.seek(0) before sending the file

You can use the tempfile module to create a named temporary file.

import tempfile
with tempfile.NamedTemporaryFile() as temp:
    temp.write(content)
    temp.flush()
    filename = temp.name
    session.storbinary('STOR {0}'.format(file_name), temp)

Here is a working example using BytesIO under io module. Code is tested and works.

import ftplib
import io
session = ftplib.FTP('192.168.1.1','USERNAME','PASSWORD')
# session.set_debuglevel(2)
buf=io.BytesIO()
# b'str' to content of buff.write() as it throws an error in python3.7
buf.write(b"test string")
buf.seek(0)
session.storbinary("STOR testfile.txt",buf)
session.quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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