【发布时间】: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