【问题标题】:How to store a CSV file uploaded via Django into a blobstore on Google App Engine?如何将通过 Django 上传的 CSV 文件存储到 Google App Engine 上的 blobstore 中?
【发布时间】:2013-06-19 04:32:36
【问题描述】:

我正在尝试通过 Django 应用将 CSV 文件上传到 Google App Engine 中的 blobstore 文件中。我遇到了一个问题,即在上传文件时转储​​文件可能会出现错误的换行符。所以,我需要在 python 的通用换行模式下打开上传的文件。 Django 文档建议我可以在 File 对象上使用 .open() 来设置新模式。

这是我提出的解决方案:

        filename = files.blobstore.create(mime_type='text/csv')
        csvfile = request.FILES.get('csvfile')

        with files.open(filename, 'a') as output_file:
            with csvfile.open(mode='rU') as input_file:
                output_file.write(input_file.readline())

(“文件”是 App Engine 的 API 的一部分)

这对我来说似乎是正确的,但我想知道是否有其他人遇到过类似的情况和更好的解决方案?

【问题讨论】:

  • FWIW,上面的代码在 csvfile 的上下文管理器的 exit 上给了我一个例外。也许我需要手动打开和关闭它?目前尚不完全清楚我什至想做的事情是否可以通过the documentation 实现。
  • 这是一个例外,对我来说这表明 Django 的 files.File 类没有实现上下文管理器协议,也许吧?即使它是 Python 文件对象的包装器? with csvfile.open(mode='rU') as input_file: AttributeError: __exit__

标签: python django google-app-engine csv blobstore


【解决方案1】:

我已经做到了。您必须迭代上传的文件

filename = files.blobstore.create(mime_type='text/csv')
csvfile = request.FILES.get('csvfile')

with files.open(filename, 'a') as output_file: 
    writer = csv.writer(output_file, quoting=csv.QUOTE_NONE)
    for row in csv.reader(csvfile.read().splitlines()):
         writer.writerow(row)

files.finalize(filename)

希望有效果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2020-03-09
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2015-02-07
    相关资源
    最近更新 更多