【问题标题】:Handling file uploads in App Engine (python)在 App Engine (python) 中处理文件上传
【发布时间】:2010-08-13 15:16:25
【问题描述】:

我正在尝试使用应用引擎和 python 实现文件上传解决方案。我正在努力检查是否真的有一个文件附加到表格中。我正在设置 enctype="multipart/form-data" 并且原则上它可以工作。我的 python 处理程序如下所示:

fileupload = self.request.POST["content"]

if not fileupload:
    return self.error(400)

如果没有附加文件,这将有效。但是,如果附加了文件,则会出现以下错误:

  File "D:\eclipse_dev\workspace\test\src\handlers.py", line 351, in post
    if not fileupload:
  File "C:\Python25\lib\cgi.py", line 633, in __len__
    return len(self.keys())
  File "C:\Python25\lib\cgi.py", line 609, in keys
    raise TypeError, "not indexable"
TypeError: not indexable

在处理程序中执行任何其他操作之前,如何安全地检查是否存在上传?

感谢您的帮助。

问候, 罗宾

【问题讨论】:

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


    【解决方案1】:

    怎么样:

    fileupload = self.request.POST["content"]
    
    if fileupload is None:
        return self.error(400)
    

    【讨论】:

    • 我试过这个,但它不会触发错误。我对python很陌生。有没有其他方法可以检查变量的值。
    【解决方案2】:

    好吧,我已经使用:

    import cgi
    .
    .
    fileupload = self.request.POST["content"]
    
    if not isinstance(fileupload, cgi.FieldStorage):
       return self.error(400)
    

    不确定这是否是最好的解决方案,但它似乎有效。

    【讨论】:

    • 这对我有用,所以我将接受我自己的答案。我希望没关系。
    【解决方案3】:

    App Engine 的 self.request.get() 方法可以很好地处理 POST 数据:

    "The request object provides a get() method that returns values for arguments parsed from the query and from POST data."

    试试这个:

    def post(self):
      fileupload = self.request.get('content')
      if not fileupload:
        self.error(400)
      else:
        # Proceed normally
    

    【讨论】:

      【解决方案4】:

      我有一个关于文件上传到 GAE 的小教程。 http://verysimplescripts.blogspot.jp/ 还包括一个完全可行的解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-18
        • 2010-09-10
        • 2013-08-25
        • 2011-02-12
        • 2013-11-25
        • 2016-01-18
        • 1970-01-01
        相关资源
        最近更新 更多