我试图从运行Python代码的Azure函数将文件输出到我的存储斑点。我已经完成了返回文件,而没有任何压缩使用以下代码:
with zipfile.ZipFile('Data_out.zip', 'w') as myzip:
myzip.write('somefile.js')
print 'adding somefile.js'
和
RFile = open('Data_out.zip', 'r').read()
output = open(os.environ['returnfile'], 'w')
output.write(RFile)
但是,一旦我开始使用任何形式的压缩形式,然后将其重新读取到绑定到我的存储斑点的文件中,最终会损坏和不可读。
import zipfile
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
modes = {zipfile.ZIP_DEFLATED: 'deflated',
zipfile.ZIP_STORED: 'stored',
}
print 'creating archive'
zf = zipfile.ZipFile('Data_out.zip', mode='w')
try:
print 'adding log.txt and outputfile with compression mode', modes[compression]
zf.write('log.txt', compress_type=compression)
zf.write('somefile.js', compress_type=compression)
finally:
print 'closing'
zf.close()
和
RFile = open('Data_out.zip', 'r').read()
output = open(os.environ['returnfile'], 'w')
output.write(RFile)
现在,这在我的WebJobs文件夹上产生了功能齐全的Zip-File。但是我无法将其正确复制到我的存储空间。我的猜测是,在处理压缩文件时,将.read((与.write((一起使用。但是目前,我不知道下一步该怎么做。
我正在使用Python 2.7。
有什么建议?
编辑
进一步阐明我正在遇到的确切错误:
使用
RFile = open('Data_out.zip', 'r').read()
output = open(os.environ['returnfile'], 'w')
output.write(RFile)
我能够完成功能脚本,但是出现在我的Azure存储BLOB中的zip文件只有几个字节,并且损坏了。我的WebJobs存储中仍在我的WebJobs存储上的zip文件实际上约为250kb,我可以将文件从中提取回我的网站。
因此,我的错误来源很可能在我的输出代码中:
RFile = open('Data_out.zip', 'r').read()
output = open(os.environ['returnfile'], 'w')
output.write(RFile)
因此,在进行了更多测试之后,我找到了解决问题的方法。我转向Python SDK进行Azure Storage。这为我提供了更多的控制。
我使用kudu安装了azure-stareage软件包(必须升级PIP才能正确安装(,然后我将软件包导入了我的脚本中,并提到了"/env/lib/site-packages"的附加引用:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'env/Lib/site-packages')))
from azure.storage.blob import BlockBlobService
我的输出方法与:https://learn.microsoft.com/en-us/azure/storage/storage-python-how-to-use-use-blob-storage。
代码最终以这样的结局:
block_blob_service = BlockBlobService(account_name='myaccount', account_key='mykey')
block_blob_service.create_container(username)
block_blob_service.create_blob_from_path(
username,
returnfile,
'Data_out.zip')
就是!