def get(self, env, start_response): """Download the tar file created by the cart""" resp = cart_interface_responses.Responses() rtn_name = None if 'filename' in parse_qs(env['QUERY_STRING']): rtn_name = os.path.basename( parse_qs(env['QUERY_STRING'])['filename'][0]) else: rtn_name = "data_" + datetime.now().strftime( '%Y_%m_%d_%H_%M_%S') + ".tar" uid = fix_cart_uid(env['PATH_INFO']) is_valid = is_valid_uid(uid) if not is_valid: self._response = resp.invalid_uid_error_response( start_response, uid) return self.return_response() #get the bundle path if available cart_utils = Cartutils() cart_path = cart_utils.available_cart(uid) if cart_path is False: #cart not ready self._response = resp.unready_cart(start_response) elif cart_path is None: #cart not found self._response = resp.cart_not_found(start_response) else: if os.path.isdir(cart_path): #give back bundle here stderr.flush() try: #want to stream the tar file out (rpipe, wpipe) = os.pipe() cpid = os.fork() # the fork screws up coverage testing... :( if cpid == 0: # pragma: no cover # we are the child process #write the data to the pipe os.close(rpipe) wfd = os.fdopen(wpipe, 'wb') mytar = TarFile.open(fileobj=wfd, mode='w|') mytar.add(cart_path, arcname=rtn_name.replace('.tar', '')) mytar.close() #to exit from the fork child without killing the parent #we need to use_exit. Disabling the pylint for this #so that it doesnt throw an error # pylint: disable=protected-access os._exit(0) # pylint: enable=protected-access # we are the parent os.close(wpipe) #open the pipe as a file rfd = os.fdopen(rpipe, 'rb') start_response( '200 OK', [('Content-Type', 'application/octet-stream'), ('Content-Disposition', 'attachment; filename=' + str(rtn_name))]) if 'wsgi.file_wrapper' in env: return env['wsgi.file_wrapper'](rfd, BLOCK_SIZE) return iter(lambda: rfd.read(BLOCK_SIZE), '') except IOError: self._response = resp.bundle_doesnt_exist(start_response) else: self._response = resp.bundle_doesnt_exist(start_response) return self.return_response() return self.return_response()
def test_bad_available_cart(self): """test getting a cart that doesnt exist""" with test_database(SqliteDatabase(':memory:'), (Cart, File)): cart_utils = Cartutils() retval = cart_utils.available_cart('2') self.assertEqual(retval, None)