从Flask请求模块读取文件 [英] Read-in Files from Flask request module
问题描述
我正在尝试从Python请求中读取文件,形成数据.我要做的就是读入请求主体中的传入文件,解析内容,然后将内容作为json主体返回.我在这里看到了很多示例,例如: if.request.files:
中的文件名",但是这对我来说永远行不通.我知道该文件实际上确实存在于ImmutableMultiDict类型内.这是我的工作代码示例:
I am trying to read-in a file from a Python request, form data. All I want to do is read-in the incoming file in the request body, parse the contents and return the contents as a json body. I see many examples out there like: if 'filename' in request.files:
, however this never works for me. I know that the file does in fact live within the ImmutableMultiDict type. Here is my working code example:
if 'my_file.xls' in request.files:
# do something
else:
# return error
推荐答案
if 'file' in request.files:
这是在寻找与您以以下形式设置的 name
属性相对应的字段名称'file'
:
This is looking for the field name 'file'
which corresponds to the name
attribute you set in the form:
<input type='file' name='file'>
然后,您需要执行类似的操作,将 FileStorage
对象分配给变量 mem
:
You then need to do something like this to assign the FileStorage
object to the variable mem
:
mem = request.files['file']
有关如何以及为什么的详细信息,请参见我最近的回答.
See my recent answer for more details of how and why.
然后您可以使用以下命令访问文件名本身:
You can then access the filename itself with:
mem.filename # should give back 'my_file.xls'
要实际读取流数据,请执行以下操作:
To actually read the stream data:
mem.read()
官方烧瓶文档对此有更多信息,以及如何使用 secure_filename()
等保存到磁盘.可能值得一读.
The official flask docs have further info on this, and how to save to disk with secure_filename()
etc. Probably worth a read.
我要做的就是在请求正文中读入文件,解析内容并将其作为json正文返回.
All I want to do is read-in the incoming file in the request body, parse the contents and return the contents as a json body.
如果您实际上想读取该Excel文件的内容,则需要使用与此兼容的库,例如 xlrd
.此答案演示了如何打开工作簿并将其作为流传递.请注意,他们使用 fileobj
作为变量名,而不是 mem
.
If you actually want to read the contents of that Excel file, then you'll need to use a library which has compatibility for this such as xlrd
. this answer demonstrates how to open a workbook, passing it as a stream. Note that they have used fileobj
as the variable name, instead of mem
.
这篇关于从Flask请求模块读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!