Handle a file-like object.

    Called by `get()` when provided a file-like. This function will prefer the
    backend's `handle_fobj()` if one is provided. Otherwise, it will write the
    data to a temporary file and call `handle_path()`.
197680
def handle_fobj(backend, f, **kwargs):
    
    if not is_binary(f):
        raise AssertionError('File must be opened in binary mode.')

    if callable(getattr(backend, 'handle_fobj', None)):
        # Prefer handle_fobj() if present.
        LOGGER.debug("using handle_fobj")
        return backend.handle_fobj(f)

    elif callable(getattr(backend, 'handle_path', None)):
        # Fallback to handle_path(). Warn user since this is potentially
        # expensive.
        LOGGER.debug("using handle_path")
        LOGGER.warning(
            "Using disk, %r backend does not provide `handle_fobj()`", backend)

        ext = ''
        if 'ext' in kwargs:
            ext = '.' + kwargs['ext']

        with fobj_to_tempfile(f, suffix=ext) as fname:
            return backend.handle_path(fname, **kwargs)
    else:
        raise AssertionError(
            'Backend %s has no _get functions' % backend.__name__)
436535
def from_file(filename_or_file_object):
    
    if isinstance(filename_or_file_object, basestring):
        file_ = open(filename_or_file_object, 'r')
        we_opened = True
    else:
        we_opened = False
        file_ = filename_or_file_object

    try:
        data = load(file_.read())
    finally:
        if we_opened:
            file_.close()

    return data
1334824
def _handle_files(self, data):
        """"""

        initial = data.get("set", False)
        files = data["files"]
        for f in files:
            try:
                fobj = File(
                    self.room,
                    self.conn,
                    f[0],
                    f[1],
                    type=f[2],
                    size=f[3],
                    expire_time=int(f[4]) / 1000,
                    uploader=f[6].get("nick") or f[6].get("user"),
                )
                self.room.filedict = fobj.fid, fobj
                if not initial:
                    self.conn.enqueue_data("file", fobj)
            except Exception:
                import pprint

                LOGGER.exception("bad file")
                pprint.pprint(f)
        if initial:
            self.conn.enqueue_data("initial_files", self.room.files)
1196467
def to_soft(self, path_or_handle, as_gzip=False):
        
        if isinstance(path_or_handle, str):
            if as_gzip:
                with gzip.open(path_or_handle, 'wt') as outfile:
                    outfile.write(self._get_object_as_soft())
            else:
                with open(path_or_handle, 'w') as outfile:
                    outfile.write(self._get_object_as_soft())
        else:
            path_or_handle.write(self._get_object_as_soft())
1361069
function() {
          return through.obj(function(file, encode, done){
            addBefore(file.path);
            this.push(file);
            done();
          });
        }
963114
function handleFile(name, file, options, cache, callback) {
	var cachedData;
	if(!options || !options.settings || options.settings['view cache'] !== false) {
		cachedData = cache && cache.get(file);
	}
	if (!cachedData) {
		loadFile(file, function(err, fileData) {
			if (err) {
				return callback(err);
			}

			var partials;
			try {
				partials = findPartials(fileData);
			} catch (err) {
				return callback(err);
			}

			var data = {
				name: name,
				data: fileData,
				partials: partials
			};
			if (cache) {
				cache.set(file, data);
			}
			return callback(null, data);
		});
	}
	else {
		return callback(null, cachedData);
	}
}
724436
def do_get(self, from_path, to_path):
        
        to_file = open(os.path.expanduser(to_path), "wb")

        self.n.downloadFile(self.current_path + "/" + from_path, to_path)
760886
def __get_file(self, file):
        
        file_object = None
        if file['name'] in request.files:
            file_object = request.files[file['name']]
            clean_filename = secure_filename(file_object.filename)
            if clean_filename == '':
                return file_object
            if file_object and self.__allowed_extension(
                    clean_filename, file['extensions']):
                return file_object
        elif file['name'] not in request.files and file['required']:
            return file_object
        return file_object
710093
function handleError(type, filepath, opts, cb) {
  return function(err) {
    switch (type) {
      case 'read':
        if (err.code === 'ENOENT') {
          err.message = formatError('file does not exist', filepath, err);
        } else {
          err.message = formatError('cannot read file', filepath, err);
        }
        break;
      case 'write':
        if (!opts.overwrite && err.code === 'EEXIST') {
          return cb();
        }
        err.message = formatError('cannot write to', filepath, err);
        break;
    }
    cb(err);
  };
}
34489
def is_filelike(obj):
    
    if isinstance(obj, (bytes, unicode)):
        return False
    res = True
    for a in ('read', 'tell', 'seek'):
        res = res and hasattr(obj, a)
    if not res:
        raise ValueError("Invalid object passed as file")
    return True
574889
def handle(self, pkt, raddress, rport):
        ""
        log.debug("In TftpStateServerRecvWRQ.handle")
        sendoack = self.serverInitial(pkt, raddress, rport)
        path = self.full_path
        if self.context.upload_open:
            f = self.context.upload_open(path, self.context)
            if f is None:
                self.sendError(TftpErrors.AccessViolation)
                raise TftpException("Dynamic path %s not permitted" % path)
            else:
                self.context.fileobj = f
        else:
            log.info("Opening file %s for writing" % path)
            if os.path.exists(path):
                # FIXME: correct behavior?
                log.warning("File %s exists already, overwriting..." % (
                    self.context.file_to_transfer))
            # FIXME: I think we should upload to a temp file and not overwrite
            # the existing file until the file is successfully uploaded.
            self.make_subdirs()
            self.context.fileobj = open(path, "wb")

        # Options negotiation.
        if sendoack:
            log.debug("Sending OACK to client")
            self.sendOACK()
        else:
            log.debug("No requested options, expecting transfer to begin...")
            self.sendACK()
        # Whether we're sending an oack or not, we're expecting a DAT for
        # block 1
        self.context.next_block = 1
        # We may have sent an OACK, but we're expecting a DAT as the response
        # to either the OACK or an ACK, so lets unconditionally use the
        # TftpStateExpectDAT state.
        return TftpStateExpectDAT(self.context)
1363318
def _serve_file(self, path):
        
        fapp = paste.fileapp.FileApp(path)
        return fapp(request.environ, self.start_response)
373832
def dump(obj, fp, pretty=False, escaped=True):
    
    if not isinstance(obj, dict):
        raise TypeError("Expected data to be an instance of``dict``")
    if not hasattr(fp, 'write'):
        raise TypeError("Expected fp to have write() method")
    if not isinstance(pretty, bool):
        raise TypeError("Expected pretty to be of type bool")
    if not isinstance(escaped, bool):
        raise TypeError("Expected escaped to be of type bool")

    for chunk in _dump_gen(obj, pretty, escaped):
        fp.write(chunk)
19353
def handle_get(self):
        

        response = self.generate_html_documentation().encode('utf-8')

        print('Content-Type: text/html')
        print('Content-Length: %d' % len(response))
        print()
        sys.stdout.flush()
        sys.stdout.buffer.write(response)
        sys.stdout.buffer.flush()
372142
def is_filelike(ob):
    
    if hasattr(ob, 'read') and callable(ob.read):
        return True

    if hasattr(ob, 'write') and callable(ob.write):
        return True

    return False
74005
def handle_get_request(self):
        
        self.objects = self.get_objects()
        self.response = self.get_response_handler()

        self.response.process(self.objects)

        return self.list_response()
331983
def file_handler(self, handler_type, path, prefixed_path, source_storage):
        
        if self.faster:
            if prefixed_path not in self.found_files:
                self.found_files[prefixed_path] = (source_storage, path)

            self.task_queue.put({
                'handler_type': handler_type,
                'path': path,
                'prefixed_path': prefixed_path,
                'source_storage': source_storage
            })
            self.counter += 1
        else:
            if handler_type == 'link':
                super(Command, self).link_file(path, prefixed_path, source_storage)
            else:
                super(Command, self).copy_file(path, prefixed_path, source_storage)