【发布时间】:2019-12-17 01:59:26
【问题描述】:
对于我当前的项目,我正在使用 python 瓶。目前,我正在尝试保存用户在表单中上传的文件,但它会引发上面显示的错误。我尽我所能遵循文档,但无论我尝试过什么,它都会出现此错误。
函数如下:
def uploadFile(file, isPublic, userId, cu, dirId=-1):
"""Takes a bottle FileUpload instance as an argument and adds it to storage/media as well as adds its
info to the database. cu should be the db cursor. isPublic should be a bool. userId should be the
uploaders id. dirId is the directory ID and defaults to -1."""
fakeName = file.filename
extension = os.path.splitext(file.filename)[1]
cu.execute("SELECT * FROM files WHERE fileId=(SELECT MAX(fileId) FROM files)")
newId = cu.fetchone()
if newId==None:
newId = 0
else:
newId = newId[1]
if debugMode:
print(f"newId {newId}")
fileName = f"userfile-{newId}-{userId}.{extension}"
file.save(vdata["m_folder"] + "/" + fileName)
cu.execute("INSERT INTO files VALUES (?, ?, ?, ?, ?, ?)",
(userId, newId, dirId, fakeName, fileName, isPublic))
cu.connection.commit()
有谁知道可能是什么问题?
【问题讨论】:
-
正如错误“对已关闭文件的 I/O 操作”中所述,您正在尝试使用已关闭的文件对象。使用 with 语句,打开文件对象然后关闭它。
-
变量和函数名应该遵循
lower_case_with_underscores风格。 -
@AlexanderCécile 你确定吗?我发现python标准库有一半时间没有遵循这个约定。
-
@AlexanderCécile 很抱歉,我目前没有任何想法,但我记得通读文档并调整我在这里使用的样式,因为我发现它是最容易阅读,但我会记住在我的下一个项目中使用
lower_case_with_underscores。 -
@AlexanderCécile
file参数是一个 bottle.py FileUpload 对象;似乎错误在于 FileUpload 对象的内部文件对象在调用file.save时尚未打开。
标签: python python-3.x bottle