bottle.py通过file.save()提高ValueError('已关闭文件的I / O操作')

时间:2019-12-16 16:49:51

标签: python python-3.x bottle

对于我当前的项目,我正在使用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()

有人知道这个问题可能是什么吗?

2 个答案:

答案 0 :(得分:1)

您似乎尚未打开文件进行写入。您可以这样做:

with open('path/to/file', 'w') as file:
    file.write('whatever')

答案 1 :(得分:1)

使用Bottle框架上传文件的示例

我不确定您是否再需要此答案,但我希望将其包含在以后的读者中。这是如何使用Bottle框架上传文件的完整示例

目录结构:

.
├── app.py
├── uploaded_files
└── views
    └── file_upload.tpl

app.py

import os
from bottle import Bottle, run, request, template

app = Bottle()

def handle_file_upload(upload):
    name, ext = os.path.splitext(upload.filename)
    if ext not in ('.png','.jpg','.jpeg'):
        return 'File extension not allowed.'

    save_path = "uploaded_files"
    upload.save(save_path) # appends upload.filename automatically
    return 'OK'

@app.route('/')
def file_upload():
    return template('file_upload')

@app.route('/upload', method='POST')
def do_upload():
    category   = request.forms.get('category')
    upload     = request.files.get('upload')
    return handle_file_upload(upload)

run(app, host='localhost', port=8080, debug=True)

views/file_upload.tpl

<form action="/upload" method="post" enctype="multipart/form-data">
  Category:      <input type="text" name="category" />
  Select a file: <input type="file" name="upload" />
  <input type="submit" value="Start upload" />
</form>

输出:

上传有效文件后的屏幕截图:

screenshot after uploading a valid file

在上述情况下可能存在的问题:

以下代码块可能会引发异常:

fileName = f"userfile-{newId}-{userId}.{extension}"
file.save(vdata["m_folder"] + "/" + fileName)

请检查每个变量的值:newIduserIdextensionvdata["m_folder"]

您还可以将"/"替换为os.sepos.path.sep

正如@AlexanderCécile在评论中提到的那样,将文件对象传递给外部方法也可能导致此问题。您可以将变量名file重命名为其他名称,但我认为它根本无法解决问题。

更新

我已经更新了代码。现在,我将文件对象发送到其他方法而不是路由功能,但是代码仍然可以正常工作。

参考:

  1. bottle official docs for file uploading