使用默認實體處理器無法獲取臨時文件的名稱。但是你可以設置你自己定製的一個來確保總是創建一個臨時文件(通常不是爲文件< 1000字節創建的)。
要在臨時文件的名稱,你需要它與CustomPart
類創建的NamedTemporaryFile
:
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
因爲做你可能無法看到該文件類在關閉時立即刪除文件。在這種情況下,只要請求完成。你可以添加一些睡眠電話這樣和驗證我剛纔說:
@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
如果你真的想保存臨時文件,那麼你只需要在delete
參數設置爲False
在NamedTemporaryFile
並結束了像這樣:
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)
你必須確保你自己刪除這些臨時文件。