Returns an OpenerDirector that supports cookies and ignores redirects.

		Returns:
			A urllib2.OpenerDirector object.
770366
def _GetOpener(self):
		
		opener = urllib2.OpenerDirector()
		opener.add_handler(urllib2.ProxyHandler())
		opener.add_handler(urllib2.UnknownHandler())
		opener.add_handler(urllib2.HTTPHandler())
		opener.add_handler(urllib2.HTTPDefaultErrorHandler())
		opener.add_handler(urllib2.HTTPSHandler())
		opener.add_handler(urllib2.HTTPErrorProcessor())
		if self.save_cookies:
			self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server)
			self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
			if os.path.exists(self.cookie_file):
				try:
					self.cookie_jar.load()
					self.authenticated = True
					StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file)
				except (cookielib.LoadError, IOError):
					# Failed to load cookies - just ignore them.
					pass
			else:
				# Create an empty cookie file with mode 600
				fd = os.open(self.cookie_file, os.O_CREAT, 0600)
				os.close(fd)
			# Always chmod the cookie file
			os.chmod(self.cookie_file, 0600)
		else:
			# Don't save cookies across runs of update.py.
			self.cookie_jar = cookielib.CookieJar()
		opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
		return opener
142852
def _polling_cookie(self):
        
        parsed_url = urlparse(self._response.request.url)
        host = parsed_url.hostname.strip('.')
        if host == 'localhost':
            return {'cookie': self._response.headers.get('set-cookie', '')}
        return {}
771858
def get_redirect(paths):
    

    if isinstance(paths, str):
        paths = [paths]

    for path in paths:
        url, permanent = get_alias(path)
        if url:
            return redirect(url, 301 if permanent else 302)

        url, permanent = current_app.get_path_regex(path)
        if url:
            return redirect(url, 301 if permanent else 302)

    return None
1089716
def resolve_redirects_if_needed(self, uri):
        
        if type(uri) == type("string") or type(uri) == type(u"unicode"):

            if uri.startswith("www."):  # support for lazy people
                uri = "http://%s" % str(uri)
            if uri.startswith("http://"):
                # headers = "Accept: application/rdf+xml"  # old way
                headers = {'Accept': "application/rdf+xml"}
                req = urllib2.Request(uri, headers=headers)
                res = urllib2.urlopen(req)
                uri = res.geturl()

        else:
            raise Exception("A URI must be in string format.")

        return uri
1078122
function createRedirectDirectoryListener () {
  return function redirect (res) {
    if (this.hasTrailingSlash()) {
      this.error(404)
      return
    }

    // get original URL
    var originalUrl = parseUrl.original(this.req)

    // append trailing slash
    originalUrl.path = null
    originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/')

    // reformat the URL
    var loc = encodeUrl(url.format(originalUrl))
    var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' +
      escapeHtml(loc) + '</a>')

    // send redirect response
    res.statusCode = 301
    res.setHeader('Content-Type', 'text/html; charset=UTF-8')
    res.setHeader('Content-Length', Buffer.byteLength(doc))
    res.setHeader('Content-Security-Policy', "default-src 'self'")
    res.setHeader('X-Content-Type-Options', 'nosniff')
    res.setHeader('Location', loc)
    res.end(doc)
  }
}
42457
def AuthenticatedOrRedirect(invocation):
    
    class AuthenticatedOrRedirect(GiottoInputMiddleware):
        def http(self, request):
            if request.user:
                return request
            return Redirection(invocation)

        def cmd(self, request):
            if request.user:
                return request
            return Redirection(invocation)

    return AuthenticatedOrRedirect
1295676
def lazy_raise_or_redirect():
    '''
    
    '''
    if not request.view_args:
        return
    for name, value in request.view_args.items():
        if isinstance(value, NotFound):
            request.routing_exception = value
            break
        elif isinstance(value, LazyRedirect):
            new_args = request.view_args
            new_args[name] = value.arg
            new_url = url_for(request.endpoint, **new_args)
            return redirect(new_url)
1091370
def get_opener(self, name):
        
        if name not in self.registry:
            raise NoOpenerError("No opener for %s" % name)
        index = self.registry[name]
        return self.openers[index]
1026492
def redirect(self, url, method=None, **kwargs):
        
        return self.nest(Redirect(url, method=method, **kwargs))
539425
def get_homepath(self, ignore_session=False, force_cookieless=False):
        
        if not ignore_session and self._session.get("session_id") is not None and self._session.get("cookieless", False):
            return web.ctx.homepath + "/@" + self._session.get("session_id") + "@"
        elif not ignore_session and force_cookieless:
            return web.ctx.homepath + "/@@"
        else:
            return web.ctx.homepath
1198725
def unauthorized_callback(self):
        
        return redirect(self.login_url(params=dict(next=request.url)))
644464
def get_authorize_url(self, redirect_uri='', **kw):
        '''
        
        '''
        return self._mixin.get_authorize_url(redirect_uri or self._mixin._redirect_uri, **kw)
47599
def clean_redirect_uri(self):
        
        redirect_uri = self.cleaned_data.get('redirect_uri')

        if redirect_uri:
            if not redirect_uri == self.client.redirect_uri:
                raise OAuthValidationError({
                    'error': 'invalid_request',
                    'error_description': _("The requested redirect didn't "
                        "match the client settings.")})

        return redirect_uri
1253338
def get_redirect_url(self, **kwargs):
        
        if self.request.REQUEST.has_key('next'): 
            return self.request.REQUEST.get('next')
        url = RedirectView.get_redirect_url(self, **kwargs)
        if url:
            return url
        return self.request.META.get('HTTP_REFERER')
1148001
def open_uri(uri, options, follows_remaining: 0)
      uri.open(options)
    rescue OpenURI::HTTPRedirect => exception
      raise Down::TooManyRedirects, "too many redirects" if follows_remaining == 0

      # fail if redirect URI scheme is not http or https
      begin
        uri = ensure_uri(exception.uri)
      rescue Down::InvalidUrl
        response = rebuild_response_from_open_uri_exception(exception)

        raise ResponseError.new("Invalid Redirect URI: #{exception.uri}", response: response)
      end

      # forward cookies on the redirect
      if !exception.io.meta["set-cookie"].to_s.empty?
        options["Cookie"] = exception.io.meta["set-cookie"]
      end

      follows_remaining -= 1
      retry
    rescue OpenURI::HTTPError => exception
      response = rebuild_response_from_open_uri_exception(exception)

      # open-uri attempts to parse the redirect URI, so we re-raise that exception
      if exception.message.include?("(Invalid Location URI)")
        raise ResponseError.new("Invalid Redirect URI: #{response["Location"]}", response: response)
      end

      response_error!(response)
    rescue => exception
      request_error!(exception)
    end
1069404
def anonymous_required(function=None, redirect_url=None):
    
    if not redirect_url:
        redirect_url = settings.LOGIN_REDIRECT_URL

    actual_decorator = user_passes_test(
        is_anonymous,
        login_url=redirect_url,
        redirect_field_name=None
    )

    if function:
        return actual_decorator(function)
    return actual_decorator
799737
def get_safe_redirect_target(arg='next'):
    
    for target in request.args.get(arg), request.referrer:
        if target:
            redirect_uri = urisplit(target)
            allowed_hosts = current_app.config.get('APP_ALLOWED_HOSTS', [])
            if redirect_uri.host in allowed_hosts:
                return target
            elif redirect_uri.path:
                return uricompose(
                    path=redirect_uri.path,
                    query=redirect_uri.query,
                    fragment=redirect_uri.fragment
                )
    return None