python - Why would an io.BytesIO stream close when passed as an argument? -
i have django app user posts file. view grabs file, passes threaded function , processes it. problem is, io.bytesio stream gets closed before can read , can't figure out why gets closed.
i'm processing excel files using xlrd library. excel files uploaded, stream stays open close. don't understand what's going on under hood figure out why. i'm asking debugging advice. can't provide full code i've outlined code path looks below.
my django view grabs file post request:
ufile = request.files['upload-file'].file
ufile
instance of io.bytesio
. have function copies stream named temporary file
@contextmanager def temp_input_file(file_): temp = tempfile.namedtemporaryfile(delete=false) shutil.copyfileobj(file_, temp) temp.close() yield temp.name os.unlink(temp.name)
this contextmanager decorated function used little later. next step create thread process uploaded file:
job.run_job( method=process_excel_file, uploaded_file=ufile )
what i'm doing passing function process_excel_file
, uploaded "file" io.bytesio
stream job.run_job, creates thread
def run_job(self, method, **kwargs): thread = threading.thread() thread.run = lambda : method( job_id=self.job_db_record.id, **kwargs ) thread.start()
so process_excel_file
passed method
variable , ufile in kwargs
. function running in thread, process_excel_file
looks this:
def process_excel_file(ufile): temp_input_file(ufile) temp_file: in_book = xlrd.open_workbook(temp_file) ... # stuff in_book
so happens when use temp_input_file
context manager function, valueerror
thrown because stream closed. if instead refactor code create temporary file in view , pass temp file name instead of file-like object, works because stream gets closed somewhere after gets passed job.run_job
. thoughts on why stream close? it's more troubling because files don't close stream.
Comments
Post a Comment