http session interface, transparent proxy to requests.session
484292
def session(self):
        
        if self._session is None:
            self._session = requests.session()
            self._session.headers.update(
                {
                    "Authorization": "Bearer {}".format(self.token),
                    "User-Agent": "ads-api-client/{}".format(__version__),
                    "Content-Type": "application/json",
                }
            )
        return self._session
822710
def session(self):
        
        if self._session is None:
            self._session = requests.Session()
            self._session.headers.update(self._headers)
        return self._session
675902
def get_session(session, baseurl, config):
    
    # Read proxy for firefox
    if environ.get("HTTP_PROXY"):
        myProxy = environ.get("HTTP_PROXY")
        proxy = Proxy({
            'proxyType': ProxyType.MANUAL,
            'httpProxy': myProxy,
            'ftpProxy': myProxy,
            'sslProxy': myProxy,
            'noProxy': ''  # set this value as desired
        })
    else:
        proxy = None

    if 'login' in config['DEFAULT']:
        login, password = credentials(config['DEFAULT']['login'])
    else:
        login, password = credentials()

    browser = webdriver.Firefox(proxy=proxy)
    browser.get(baseurl)
    browser.find_element_by_name('login').send_keys(login)
    browser.find_element_by_name('passwd').send_keys(password)

    cookie = {'PHPSESSID': browser.get_cookie('PHPSESSID')['value']}
    prof_session.cookies = requests.utils.cookiejar_from_dict(cookie)
    print("Please log using firefox")
    while True:
        try:
            browser.find_element_by_css_selector("select")
            break
        except:
            sleep(0.5)
    browser.close()
    set_sessid(cookie['PHPSESSID'])
    if not verify_session(session, baseurl):
        print("Cannot get a valid session, retry")
        get_session(session, baseurl, {'DEFAULT': {}})
1366647
def InitHttp(api_endpoint=None,
             page_size=None,
             auth=None,
             proxies=None,
             verify=None,
             cert=None,
             trust_env=True):
  """"""

  connector = http_connector.HttpConnector(
      api_endpoint=api_endpoint,
      page_size=page_size,
      auth=auth,
      proxies=proxies,
      verify=verify,
      cert=cert,
      trust_env=trust_env)

  return GrrApi(connector=connector)
628452
def set_proxy(url, basic_auth=None):
    
    global _pools, _onetime_pool_spec
    if not url:
        _pools['default'] = urllib3.PoolManager(**_default_pool_params)
        _onetime_pool_spec = (urllib3.PoolManager, _onetime_pool_params)
    elif basic_auth:
        h = urllib3.make_headers(proxy_basic_auth=':'.join(basic_auth))
        _pools['default'] = urllib3.ProxyManager(url, proxy_headers=h, **_default_pool_params)
        _onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=url, proxy_headers=h, **_onetime_pool_params))
    else:
        _pools['default'] = urllib3.ProxyManager(url, **_default_pool_params)
        _onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=url, **_onetime_pool_params))
609865
def app(session_id, app, bind, port):
    
    api_session = None
    runner = None

    async def app_setup():
        nonlocal api_session, runner
        loop = current_loop()
        api_session = AsyncSession()
        # TODO: generalize protocol using service ports metadata
        protocol = 'http'
        runner = ProxyRunner(api_session, session_id, app,
                             protocol, bind, port,
                             loop=loop)
        await runner.ready()
        print_info(
            "A local proxy to the application \"{0}\" ".format(app) +
            "provided by the session \"{0}\" ".format(session_id) +
            "is available at: {0}://{1}:{2}"
            .format(protocol, bind, port)
        )

    async def app_shutdown():
        nonlocal api_session, runner
        print_info("Shutting down....")
        await runner.close()
        await api_session.close()
        print_info("The local proxy to \"{}\" has terminated."
                   .format(app))

    asyncio_run_forever(app_setup(), app_shutdown(),
                        stop_signals={signal.SIGINT, signal.SIGTERM})
653874
def proxy_callback(request):
    

    pgtIou = request.GET.get('pgtIou')
    tgt = request.GET.get('pgtId')

    if not (pgtIou and tgt):
        logger.info('No pgtIou or tgt found in request.GET')
        return HttpResponse('No pgtIOO', content_type="text/plain")

    try:
        PgtIOU.objects.create(tgt=tgt, pgtIou=pgtIou, created=datetime.datetime.now())
        request.session['pgt-TICKET'] = pgtIou
        return HttpResponse('PGT ticket is: {ticket}'.format(ticket=pgtIou), content_type="text/plain")
    except Exception as e:
        logger.warning('PGT storage failed. {message}'.format(
            message=e
        ))
        return HttpResponse('PGT storage failed for {request}'.format(request=str(request.GET)),
                            content_type="text/plain")
554037
function proxy(options) {
  var proxy = null
    , isSSL = false
    ;

  if (options.protocol === 'https:') {
    isSSL = true;
  }

  // Test the proxy parameter first for priority
  if (proxyOptions) {
    proxy = proxyOptions;
  } else {
    // Test proxy by env
    if (proxyHttpEnv) {
      proxy = proxyHttpEnv;
    } else if (proxyHttpsEnv) {
      proxy = proxyHttpsEnv;
    }
  }

  if (!proxy) {
    return;
  }

  if (isSSL) {
    options.agent = new HttpsProxyAgent(proxy);
  } else {
    options.agent = new HttpProxyAgent(proxy);
  }
}
925503
function _proxy(rule, metas) {
  var opts = _getRequestOpts(metas.req, rule);
  var request = httpsSyntax.test(rule.replace) ? httpsReq : httpReq;

  var pipe = request(opts, function (res) {
    res.headers.via = opts.headers.via;
    metas.res.writeHead(res.statusCode, res.headers);
    res.on('error', function (err) {
      metas.next(err);
    });
    res.pipe(metas.res);
  });

  pipe.on('error', function (err) {
    metas.next(err);
  });

  if(!metas.req.readable) {
    pipe.end();
  } else {
    metas.req.pipe(pipe);
  }
}
639517
def _get_requests_session():
    """"""
    global requests_session
    if requests_session is not None:
        return requests_session
    import requests

    requests_session = requests.Session()
    adapter = requests.adapters.HTTPAdapter(
        max_retries=environments.PIPENV_MAX_RETRIES
    )
    requests_session.mount("https://pypi.org/pypi", adapter)
    return requests_session
1050682
def http_resource(self, method, url, params=None, data=None):
        

        url = urllib_parse.urljoin(self.url, url)
        url = url if url.endswith("/") else url + "/"

        headers = None

        if method.lower() in self.unsupported_methods:
            headers = {"X-HTTP-Method-Override": method.upper()}
            method = "POST"

        r = self.session.request(method, url, params=params, data=data, headers=headers)

        r.raise_for_status()

        return r
563219
def _setup_http_session(self):
        
        headers = {"Content-type": "application/json"}
        if (self._id_token):
            headers.update({"authorization": "Bearer {}".format(
                self._id_token)})
        self._session.headers.update(headers)
        # TODO is this unsafe????
        self._session.verify = False
1070025
async def set_http_proxy(cls, url: typing.Optional[str]):
        """"""
        await cls.set_config("http_proxy", "" if url is None else url)
814843
def _create_session(self):
        
        self.driver = requests.Session(**self.driver_args)
        # Set default headers
        self.update_headers(self.current_headers)
        self.update_cookies(self.current_cookies)
        self.set_proxy(self.current_proxy)
891031
function Session(req, res, cookies, opts) {
  this.req = req;
  this.res = res;
  this.cookies = cookies;
  this.opts = opts;
  if (opts.cookie.ephemeral && opts.cookie.maxAge) {
    throw new Error("you cannot have an ephemeral cookie with a maxAge.");
  }

  this.content = {};
  this.json = JSON.stringify(this._content);
  this.loaded = false;
  this.dirty = false;

  // no need to initialize it, loadFromCookie will do
  // via reset() or unbox()
  this.createdAt = null;
  this.duration = opts.duration;
  this.activeDuration = opts.activeDuration;

  // support for maxAge
  if (opts.cookie.maxAge) {
    this.expires = new Date(new Date().getTime() + opts.cookie.maxAge);
  } else {
    this.updateDefaultExpires();
  }

  // here, we check that the security bits are set correctly
  var secure = (res.socket && res.socket.encrypted) ||
      (req.connection && req.connection.proxySecure);
  if (opts.cookie.secure && !secure) {
    throw new Error("you cannot have a secure cookie unless the socket is " +
        " secure or you declare req.connection.proxySecure to be true.");
  }
}
153171
def set_proxy (self, proxy):
        
        self.proxy = proxy
        self.proxytype = "http"
        self.proxyauth = None
        if not self.proxy:
            return
        proxyurl = urlparse.urlparse(self.proxy)
        self.proxytype = proxyurl.scheme
        if self.proxytype not in ('http', 'https'):
            # Note that invalid proxies might raise TypeError in urllib2,
            # so make sure to stop checking at this point, not later.
            msg = _("Proxy value `%(proxy)s' must start with 'http:' or 'https:'.") \
                 % dict(proxy=proxy)
            raise LinkCheckerError(msg)
        if self.ignore_proxy_host():
            # log proxy without auth info
            log.debug(LOG_CHECK, "ignoring proxy %r", self.proxy)
            self.add_info(_("Ignoring proxy setting `%(proxy)s'.") %
                dict(proxy=proxy))
            self.proxy = None
            return
        log.debug(LOG_CHECK, "using proxy %r", self.proxy)
        self.add_info(_("Using proxy `%(proxy)s'.") % dict(proxy=self.proxy))
        self.proxyhost = proxyurl.hostname
        self.proxyport = proxyurl.port
        if proxyurl.username is not None:
            username = proxyurl.username
            password = proxyurl.password if proxy.password is not None else ""
            auth = "%s:%s" % (username, password)
            self.proxyauth = "Basic "+httputil.encode_base64(auth)
165352
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler:
        
        if self.server:
            return ConnectionHandler("https", "wss", self.server, self.port, self.path, session, proxy)
        elif self.ipv6:
            return ConnectionHandler("https", "wss", "[{0}]".format(self.ipv6), self.port, self.path, session, proxy)

        return ConnectionHandler("https", "wss", self.ipv4, self.port, self.path, session, proxy)