通过 FTP 从内存发送 JSON 对象

问题描述

我已经将蜘蛛部署到了scrapyd。在开发中,蜘蛛正在将文件写入磁盘。 部署没有文件产生。我相信这是一个权限问题。我正在寻找 ftp 数据。因此,解决方案 1 根本不写入文件。有没有办法在不先创建文件的情况下获取 dict 对象列表并将它们 ftp 出来?或者 2: 是一个临时文件一个可行的选择 & 权限是否会更容易。或者3,我可以给scrapyd守护进程更多的权限吗?

谢谢,

吉姆

mOutput = dict() dict_list = [] 对于 tableRows 中的单位:

            mOutput = {
                'model': units.xpath(".//td[1]/text()").get().replace('\xa0',''),'modelName': units.xpath(".//td[2]/text()").get(),'oct': units.xpath(".//td[3]/text()").get(),'nov': units.xpath(".//td[4]/text()").get(),'dec': units.xpath(".//td[5]/text()").get(),'jan': units.xpath(".//td[6]/text()").get(),'feb': units.xpath(".//td[7]/text()").get(),'mar': units.xpath(".//td[8]/text()").get(),'apr': units.xpath(".//td[9]/text()").get(),'may': units.xpath(".//td[10]/text()").get(),'jun': units.xpath(".//td[11]/text()").get(),'july': units.xpath(".//td[12]/text()").get(),'total': units.xpath(".//td[14]/text()").get(),'shipped': units.xpath(".//td[14]/text()").get()                   
            } 
            dict_list.append(mOutput)
        
        objToFTP = json.dumps(dict_list)

解决方法

此方法接受 objToFTP 作为输入。所以,我不再需要在本地创建一个 f 文件。请务必添加这些导入:

导入io, 从 ftplib 导入 FTP

def sendFile(self,data):
        with FTP('192.168.0.101') as ftp:
            ftp.login()
            bio = io.BytesIO()
            bio.write(data.encode())
            bio.seek(0)  # move to beginning of file
            ftp.storbinary('STOR data.json',bio)                                            
            ftp.quit() #probably don't neeed this