使用webapp和Django表单将文件上传到App Engine [英] Uploading files to App Engine using webapp and Django forms

查看:110
本文介绍了使用webapp和Django表单将文件上传到App Engine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本问题是:是否有相当于

My basic question is this: Is there an equivalent of

form = MyForm(request.POST, request.FILES)

当使用 webapp 框架处理文件上传时在Google App Engine上?

when handling file uploads using the webapp framework on Google App Engine?

我知道我可以使用 self.request.get('field_name')或使用 self.request.params ['field_name'] 的FieldStorage对象,但在我的情况下,我不提前知道字段名称。我想让表单对象把它需要的数据从请求中拉出来(特别是因为表单,所以输入的字段名称有前缀)。

I know that I can pull out specific uploaded file data using self.request.get('field_name') or a FieldStorage object using self.request.params['field_name'], but in my case I do not know the field names in advance. I would like to let the form object take care of pulling the data it needs out of the request (especially since the forms, and thus the incoming field names, have prefixes).

我正在从Django(已经在App Engine上运行)移植到一个通用的CMS系统到Google的webapp框架,这是最后一个主要的绊脚石。当创建一个新项目时,我希望能够将POSTed参数和文件直接传递给该项目的Django表单对象,以便我不必提前知道表单中的哪些字段哪些字段是文件上传。这是可以使用Django,但我看不到任何简单的方法来做它在webapp框架。

I'm porting a sort of generic CMS system from Django (already running on App Engine) to Google's webapp framework, and this is the last major stumbling block. When a new item is created, I'd like to be able to just pass the POSTed parameters and files straight to the Django form object for that item, so that I don't have to know ahead of time what fields are in the form and which of those fields are file uploads. This was possible using Django, but I can't see any easy way to do it in the webapp framework.

推荐答案

这是解决方案我想出了我添加了以下方法到我的自定义 webapp.RequestHandler 子类:

Here's the solution I came up with. I added the following method to my custom webapp.RequestHandler subclass:

# Required imports
import cgi
from django.core.files.uploadedfile import SimpleUploadedFile

def get_uploaded_files(self):
    """Gets a dictionary mapping field names to SimpleUploadedFile objects
    for each uploaded file in the given params.  Suitable for passing to a
    Django form as the `files` argument."""
    return dict((k, SimpleUploadedFile(v.filename, v.file.read()))
                for k, v in self.request.params.items()
                if isinstance(v, cgi.FieldStorage) and v.file)

现在,处理上传的文件时,可以执行以下操作:

Now, when handling uploaded files, I can do something like the following:

form = MyForm(self.request.params, self.get_uploaded_files())

这对我来说很好,迄今为止。

This works well for me so far.

(我不知道这是不好的形式来回答我自己的q题目了。对不起,如果是的话。)

(I don't know if it's bad form to answer my own question. I'm sorry if it is.)

这篇关于使用webapp和Django表单将文件上传到App Engine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆