【问题标题】:upload file to google storage using Python Google App engine API使用 Python Google App Engine API 将文件上传到谷歌存储
【发布时间】:2016-01-24 12:10:27
【问题描述】:

我正在关注 Massimiliano Pippi 的 Python for Google App 引擎。在第 3 章中,我们正在尝试上传我的应用程序的用户通过以下 html 代码选择的文件:

<div class="form-group">
            <label for="uploaded_file">Attached file:</label>
            <input type="file" id="uploaded_file" name="uploaded_file">
</div>

从 python 部分,在 webapp2 上的 MainHandler 中,我使用以下方式获取请求内容:

def post(self):
    uploaded_file = self.request.POST.get("uploaded_file", None)
    file_name = getattr(uploaded_file, 'filename')
    file_content = getattr(uploaded_file, 'file', None)
    content_t = mimetypes.guess_type(file_name)[0]

    bucket_name = app_identity.get_default_gcs_bucket_name()
    path = os.path.join('/', bucket_name, file_name)
    with cloudstorage.open(path, 'w', content_type=content_t) as f:
        f.write(file_content.read())

问题在于变量 uploaded_file 被处理为好像是由 Massimiliano Pippi 处理的文件,但我的 Python 告诉我这个变量是包含文件名称的 unicode。因此,当我尝试file_name = getattr(uploaded_file, 'filename') 时,会出现错误。

很明显,书中的代码是假的,我该如何解决呢?

【问题讨论】:

  • 我没看过那本书,你也没说你用的是webapp2。如果你的底层请求对象是使用 WebOb 构建的。 WebOb 使用 cgi.FieldStorage 对象来保存文件内容。阅读 WebOb(如果 webapp2 的上下文为真)并查看请求对象的内容,看看那里有什么。在开发服务器上添加战略性import pdb; pdb.set_trace() 并使用调试器将教你很多关于请求对象如何工作的知识。
  • 是的,我正在使用 webapp2。我会在 WebOb 上查看文档,感谢您的提示。

标签: python file google-app-engine upload google-cloud-storage


【解决方案1】:

好的,所以在 Tim 的建议下,我检查了 WebOb 的文档,并注意到在 html 文件中,我应该将enctype="multipart/form-data" 如下所示:

<form action="" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="uploaded_file">Attached file:</label>
        <input type="file" id="uploaded_file" name="uploaded_file">
    </div>
</form>

代替:

<form action="" method="post">
    <div class="form-group">
        <label for="uploaded_file">Attached file:</label>
        <input type="file" id="uploaded_file" name="uploaded_file">
    </div>
</form>

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 2014-11-22
    • 2020-08-21
    • 2014-08-03
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多