简体   繁体   English

Python - 即时创建 txt 文件并通过 FTP 发送?

[英]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?所以我目前正在从 jinja2 模板动态创建一个文本文件,并让用户浏览器下载它,但是我想添加一个选项,通过 FTP 将它发送到某个地方(所有 FTP 详细信息都是预定义的并且不会改变)如何创建要发送的文件?

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需要在发送文件之前添加 temp.seek(0)

You can use the tempfile module to create a named temporary file.您可以使用tempfile模块创建一个命名的临时文件。

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.这是一个在io模块下使用BytesIO的工作示例。 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()

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

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