CherryPy 获取上传文件的临时位置

CherryPy get uploaded file's temporary location

在 CherryPy 中上传文件:

    def upload(self, myFile):
        out = """File name: %s, Content-Type: %"""
        return out % (myFile.filename, myFile.content_type)
    upload.exposed = True

来自docs

When a client uploads a file to a CherryPy application, it’s placed on disk immediately. CherryPy will pass it to your exposed method as an argument (see “myFile” below); that arg will have a “file” attribute, which is a handle to the temporary uploaded file. If you wish to permanently save the file, you need to read() from myFile.file and write() somewhere else.

如何获取上传文件的临时位置?

您无法使用默认实体处理器获取临时文件的名称。但是您可以设置自己的自定义文件以确保始终创建临时文件(通常不会为 <1000 字节的文件创建)。

要在临时文件中有一个名称,您需要一个 NamedTemporaryFile,它是使用 CustomPart class:

创建的
import tempfile
import cherrypy as cp

class App:

    @cp.expose
    def index(self):
        return """
        <html><body>
            <h2>Upload a file</h2>
            <form action="upload" method="post" enctype="multipart/form-data">
            filename: <input type="file" name="my_file" /><br />
            <input type="submit" />
            </form>
        </body></html>
        """

    @cp.expose
    def upload(self, my_file):
        return "The path is %s" % my_file.file.name


class CustomPart(cp._cpreqbody.Part):
    """
    Custom entity part that it will alway create a named
    temporary file for the entities.
    """
    maxrambytes = 0 # to ensure that it doesn't store it in memory

    def make_file(self):
        return tempfile.NamedTemporaryFile()


if __name__ == '__main__':
    cp.quickstart(App(), config={
        '/': {
            'request.body.part_class': CustomPart
        }
    })

请求完成后您将无法看到该文件,因为默认情况下 NamedTemporaryFile class 会在文件关闭后立即删除该文件。在这种情况下,只要请求完成。您可以像这样添加一些睡眠调用并验证我刚才所说的内容:

   @cp.expose
   def upload(self, my_file):
        import time
        cp.log.error("You have 30 seconds to open the temporary file %s" % my_file.file.name)
        time.sleep(30)
        return "The path is %s" % my_file.file.name

如果你真的想保留临时文件,那么你只需要在 NamedTemporaryFile 上将 delete 参数设置为 False 并以这样的方式结束:

 class CustomPart(cp._cpreqbody.Part):
        """
        Custom entity part that it will alway create a named
        temporary file for the entities.
        """
        maxrambytes = 0 # to ensure that it doesn't store it in memory

        def make_file(self):
            return tempfile.NamedTemporaryFile(delete=False)

您必须确保自行删除这些临时文件。