Resolve a remote ``uri``.

    .. note::

        urllib library is used to fetch requests from the remote ``uri``
        if handlers does notdefine otherwise.
429639
def resolve_remote(uri, handlers):
    
    scheme = urlparse.urlsplit(uri).scheme
    if scheme in handlers:
        result = handlers[scheme](uri)
    else:
        req = urlopen(uri)
        encoding = req.info().get_content_charset() or 'utf-8'
        result = json.loads(req.read().decode(encoding),)
    return result
39209
def resolve_redirects(self, resp, req, stream=False, timeout=None,
                          verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
        """"""

        hist = []  # keep track of history

        url = self.get_redirect_target(resp)
        while url:
            prepared_request = req.copy()

            # Update history and keep track of redirects.
            # resp.history must ignore the original request in this loop
            hist.append(resp)
            resp.history = hist[1:]

            try:
                resp.content  # Consume socket so it can be released
            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
                resp.raw.read(decode_content=False)

            if len(resp.history) >= self.max_redirects:
                raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)

            # Release the connection back into the pool.
            resp.close()

            # Handle redirection without scheme (see: RFC 1808 Section 4)
            if url.startswith('//'):
                parsed_rurl = urlparse(resp.url)
                url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)

            # The scheme should be lower case...
            parsed = urlparse(url)
            url = parsed.geturl()

            # Facilitate relative 'location' headers, as allowed by RFC 7231.
            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
            # Compliant with RFC3986, we percent encode the url.
            if not parsed.netloc:
                url = urljoin(resp.url, requote_uri(url))
            else:
                url = requote_uri(url)

            prepared_request.url = to_native_string(url)

            self.rebuild_method(prepared_request, resp)

            # https://github.com/requests/requests/issues/1084
            if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
                # https://github.com/requests/requests/issues/3490
                purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')
                for header in purged_headers:
                    prepared_request.headers.pop(header, None)
                prepared_request.body = None

            headers = prepared_request.headers
            try:
                del headers['Cookie']
            except KeyError:
                pass

            # Extract any cookies sent on the response to the cookiejar
            # in the new request. Because we've mutated our copied prepared
            # request, use the old one that we haven't yet touched.
            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
            merge_cookies(prepared_request._cookies, self.cookies)
            prepared_request.prepare_cookies(prepared_request._cookies)

            # Rebuild auth and proxy information.
            proxies = self.rebuild_proxies(prepared_request, proxies)
            self.rebuild_auth(prepared_request, resp)

            # A failed tell() sets `_body_position` to `object()`. This non-None
            # value ensures `rewindable` will be True, allowing us to raise an
            # UnrewindableBodyError, instead of hanging the connection.
            rewindable = (
                prepared_request._body_position is not None and
                ('Content-Length' in headers or 'Transfer-Encoding' in headers)
            )

            # Attempt to rewind consumed file-like object.
            if rewindable:
                rewind_body(prepared_request)

            # Override the original request.
            req = prepared_request

            if yield_requests:
                yield req
            else:

                resp = self.send(
                    req,
                    stream=stream,
                    timeout=timeout,
                    verify=verify,
                    cert=cert,
                    proxies=proxies,
                    allow_redirects=False,
                    **adapter_kwargs
                )

                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)

                # extract redirect url, if any, for the next loop
                url = self.get_redirect_target(resp)
                yield resp
834384
def _load_url(url):
    
    try:
        response = requests.get(url)
        return BytesIO(response.content)
    except IOError as ex:
        parser.error("{url} could not be loaded remotely! ({ex})".format(url=url, ex=ex))
974719
def get_search_url(self):
        

        if self.is_remote:
            return self.url

        return reverse('search_api', args=[self.slug])
994880
def get_by_uri(self, uri):
        
        self._helper.validate_resource_uri(uri)
        data = self._helper.do_get(uri)

        if data:
            new_resource = self.new(self._connection, data)
        else:
            new_resource = None

        return new_resource
389670
def resolve(self, space_id=None, environment_id=None):
        

        proxy_method = getattr(
            self._client,
            base_path_for(self.link_type)
        )
        if self.link_type == 'Space':
            return proxy_method().find(self.id)
        elif environment_id is not None:
            return proxy_method(space_id, environment_id).find(self.id)
        else:
            return proxy_method(space_id).find(self.id)
1125870
def _get(self, uri, params=None, headers=None):
        
        if not headers:
            headers = self._get_headers()

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))

        response = self.session.get(uri, headers=headers, params=params)
        logging.debug("STATUS=" + str(response.status_code))
        if response.status_code == 200:
            return response.json()
        else:
            logging.error(b"ERROR=" + response.content)
            response.raise_for_status()
1040337
def uri_read(*args, **kwargs):
    

    with uri_open(*args, **kwargs) as f:
        content = f.read()
    return content
948065
function retrieve(uri, callback) {
  var buffer = '';
  http.get(uri, function(res) {
    res.on('data', function (chunk) {
      buffer += chunk;
    });
    res.on('end', function() {
      callback(null, buffer);
    });
  }).on('error', function(e) {
    callback(e);
  });
}
608019
def make_handler(f, remote, with_response=True):
    
    if isinstance(f, six.string_types):
        f = import_string(f)

    @wraps(f)
    def inner(*args, **kwargs):
        if with_response:
            return f(args[0], remote, *args[1:], **kwargs)
        else:
            return f(remote, *args, **kwargs)
    return inner
838365
def resolve_url(self, resource_name):
        """"""

        if self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE:
            # For CSV packages, need to get the package and open it to get the resoruce URL, becuase
            # they are always absolute web URLs and may not be related to the location of the metadata.
            s = self.get_resource()
            rs = s.doc.resource(resource_name)
            return parse_app_url(rs.url)
        else:
            jt = self.join_target(resource_name)
            rs = jt.get_resource()
            t = rs.get_target()
        return t
822549
def resolve_url_ext(to, params_=None, anchor_=None, args=None, kwargs=None):
    
    url = resolve_url(to, *(args or ()), **(kwargs or {}))
    if params_:
        url += '?' + urllib.urlencode(encode_url_query_params(params_))
    if anchor_:
        url += '#' + anchor_
    return url
799044
def perform_remote_action(i):
    

    # Import modules compatible with Python 2.x and 3.x
    import urllib

    try:    import urllib.request as urllib2
    except: import urllib2 # pragma: no cover

    try:    from urllib.parse import urlencode
    except: from urllib import urlencode # pragma: no cover

    rr={'return':0}

    # Get action
    act=i.get('action','')

    # Check output
    o=i.get('out','')

    if o=='con':
#       out('Initiating remote access ...')
#       out('')
       i['out']='con'
       i['quiet']='yes'
       if act=='pull':
          i['out']='json'
    else:
       i['out']='json'

#    # Clean up input
#    if o!='json_file': 
#       rr['out']='json' # Decided to return json to show that it's remote ...

    if 'cid' in i: 
       del(i['cid']) # already processed

    # Get URL
    url=i.get('remote_server_url','')

    # Process i
    if 'remote_server_url' in i: del(i['remote_server_url'])

    # Pre process if push file ...
    if act=='push':
       # Check file
       fn=i.get('filename','')
       if fn=='':
          x=i.get('cids',[])
          if len(x)>0:
             fn=x[0]

       if fn=='':
          return {'return':1, 'error':'filename is empty'}

       if not os.path.isfile(fn):
          return {'return':1, 'error':'file '+fn+' not found'}

       rx=convert_file_to_upload_string({'filename':fn})
       if rx['return']>0: return rx

       i['file_content_base64']=rx['file_content_base64']

       # Leave only filename without path
       i['filename']=os.path.basename(fn)

    # Prepare post variables
    r=dumps_json({'dict':i, 'skip_indent':'yes'})
    if r['return']>0: return r
    s=r['string'].encode('utf8')

    post=urlencode({'ck_json':s})
    if sys.version_info[0]>2: post=post.encode('utf8')

    # If auth
    au=i.get('remote_server_user','')
    if au!='': 
       del(i['remote_server_user'])

       ap=i.get('remote_server_pass','')
       if ap!='': 
          del(i['remote_server_pass'])

       auth = urllib2.HTTPPasswordMgrWithDefaultRealm()
       auth.add_password(None, url, au, ap)
       urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth)))

    # Prepare request
    request = urllib2.Request(url, post)

    # Connect
    try:
       f=urllib2.urlopen(request)
    except Exception as e:
       return {'return':1, 'error':'Access to remote CK repository failed ('+format(e)+')'}

    # Read from Internet
    try:
       s=f.read()
       f.close()
    except Exception as e:
       return {'return':1, 'error':'Failed reading stream from remote CK web service ('+format(e)+')'}

    # Check output
    try: s=s.decode('utf8')
    except Exception as e: pass
    if o=='con' and act!='pull':
       out(s.rstrip())
    else:
       # Try to convert output to dictionary
       r=convert_json_str_to_dict({'str':s, 'skip_quote_replacement':'yes'})
       if r['return']>0: 
          return {'return':1, 'error':'can\'t parse output from remote CK server ('+r['error']+'):\n'+s[:256]+'\n\n...)'}

       d=r['dict']

       if 'return' in d: d['return']=int(d['return']) # Fix for some strange behavior when 'return' is not integer - should check why ...

       if d.get('return',0)>0:
          return d

       # Post process if pull file ...
       if act=='pull':
          if o!='json' and o!='json_file':
             # Convert encoded file to real file ...
             x=d.get('file_content_base64','')

             fn=d.get('filename','')
             if fn=='': fn=cfg['default_archive_name']

             r=convert_upload_string_to_file({'file_content_base64':x, 'filename':fn})
             if r['return']>0: return r

             if 'file_content_base64' in d: del(d['file_content_base64'])

       rr.update(d)

    # Restore original output
    i['out']=o

    return rr
1032585
def _resolved_url(self):
        """"""

        if not self.url:
            return None

        u = parse_app_url(self.url)

        if u.scheme == 'index':
            u = u.resolve()

        if u.scheme != 'file':
            # Hopefully means the URL is http, https, ftp, etc.

            return u
        elif u.resource_format == 'ipynb':

            # This shouldn't be a special case, but ...
            t = self.doc.package_url.inner.join_dir(self.url)
            t = t.as_type(type(u))
            t.fragment = u.fragment

            return t

        elif u.proto == 'metatab':

            u = self.expanded_url

            return u.get_resource().get_target()

        elif u.proto == 'metapack':

            u = self.expanded_url

            if u.resource:
                return u.resource.resolved_url.get_resource().get_target()
            else:
                return u

        if u.scheme == 'file':

            return self.expanded_url

        elif False:


            assert isinstance(self.doc.package_url, MetapackPackageUrl), (type(self.doc.package_url), self.doc.package_url)

            try:
                t = self.doc.package_url.resolve_url(self.url) # Why are we doing this?

                # Also a hack
                t.scheme_extension = parse_app_url(self.url).scheme_extension

                # Another Hack!
                try:
                    if not any(t.fragment) and any(u.fragment):
                        t.fragment = u.fragment
                except TypeError:
                    if not t.fragment and u.fragment:
                        t.fragment = u.fragment


                # Yet more hack!
                t = parse_app_url(str(t))

                return t

            except ResourceError as e:
                # This case happens when a filesystem packages has a non-standard metadata name
                # Total hack
                raise

        else:
            raise ResourceError('Unknown case for url {} '.format(self.url))
1077273
def parse_uri
      self.uri = URI.parse(raw_url)
      uri.path = "/" if uri.path.empty?
      uri.fragment = nil
      # if this fails, mark the URL as invalid
    rescue
      self.valid = false
    end
342098
def resolve url
      url.gsub!(/\{([a-zA-Z0-9_]+)\}/) do |s|
        s.gsub!(/[\{\}]/, '')
        if instance_variable_defined?("@#{s}")
          instance_variable_get("@#{s}")
        else
          raise 'Did you forget to "grab" ' + s + '?'
        end
      end
      url
    end
768004
def _resolve(self, path, method, urlargs=None):
        '''
        '''
        match = self.route.match(path)
        if match is None:
            if not self.route.is_leaf:  # no match
                return
        elif '__remaining__' in match:
            path = match.pop('__remaining__')
            urlargs = update_args(urlargs, match)
        else:
            handler = getattr(self, method, None)
            if handler is None:
                raise MethodNotAllowed
            response_wrapper = self.response_wrapper
            if response_wrapper:
                handler = partial(response_wrapper, handler)
            return Handler(self, handler, update_args(urlargs, match))
        #
        for handler in self.routes:
            view_args = handler._resolve(path, method, urlargs)
            if view_args is None:
                continue
            return view_args