Create a requests Session object

        :param Path token_path: (Only oauth) full path to where the token
         should be load from
        :return: A ready to use requests session
        :rtype: OAuth2Session
960545
def get_session(self, token_path=None):
        
        # TODO: remove token_path in future versions
        if token_path is not None:
            warnings.warn('"token_path" param will be removed in future versions.'
                          ' Use a TokenBackend instead.', DeprecationWarning)

        # gets a fresh token from the store
        token = self.token_backend.get_token()

        if token:
            client_id, _ = self.auth
            session = OAuth2Session(client_id=client_id, token=token)
        else:
            raise RuntimeError(
                'No auth token found. Authentication Flow needed')

        session.proxies = self.proxy

        if self.request_retries:
            retry = Retry(total=self.request_retries, read=self.request_retries,
                          connect=self.request_retries,
                          backoff_factor=RETRIES_BACKOFF_FACTOR,
                          status_forcelist=RETRIES_STATUS_LIST)
            adapter = HTTPAdapter(max_retries=retry)
            session.mount('http://', adapter)
            session.mount('https://', adapter)

        return session
238977
def preauthChild(self, path):
        
        newpath = abspath(joinpath(self.path, normpath(path)))
        if not newpath.startswith(self.path):
            raise InsecurePath("%s is not a child of %s" % (newpath, self.path))
        return self.clonePath(newpath)
662544
def refresh_token(token, session=None):
    
    session = session or HTTP_SESSION
    refresh_data = dict(
        refresh_token=token.refresh_token,
        client_id=token.consumer_key,
        client_secret=token.consumer_secret,
        grant_type='refresh_token'
    )
    resp = session.post(REFRESH_TOKEN_URL, data=refresh_data)
    resp_json = resp.json()
    if 'error' in resp_json:
        message = resp_json['error']
        description = resp_json.get('error_description', '')
        if any(description):
            message = u'{}: {}'.format(message, description)
        raise OAuthTokenExpiredError(message)
    return OAuthToken(
        access_token=resp_json['access_token'],
        refresh_token=token.refresh_token,
        consumer_key=token.consumer_key,
        consumer_secret=token.consumer_secret
    )
475827
def delete(self, path):
        
        return self.session.delete(self._request_url(path),
                                   auth=self.auth, verify=False)
1229327
def get_token(self):
        
        token = None
        if self.token_path.exists():
            with self.token_path.open('r') as token_file:
                token = self.token_constructor(self.serializer.load(token_file))
        self.token = token
        return token
743945
def oauth_token_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/oauth/tokens.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
104987
def get_session_token(self, resource_path):
        

        with self.session_lock:
            is_name_based = base.IsNameBased(resource_path)
            collection_rid = ''
            session_token = ''

            try:
                if is_name_based:
                    # get the collection name
                    collection_name = base.GetItemContainerLink(resource_path)
                    collection_rid = self.collection_name_to_rid[collection_name]
                else:
                    collection_rid = base.GetItemContainerLink(resource_path)

                if collection_rid in self.rid_to_session_token:
                    token_dict = self.rid_to_session_token[collection_rid]
                    session_token_list = []
                    for key in token_dict.keys():
                        session_token_list.append("{0}:{1}".format(key, token_dict[key].convert_to_string()))
                    session_token = ','.join(session_token_list)
                    return session_token
                else:
                    # return empty token if not found 
                    return ''
            except: 
                return ''
479381
def requests_session(self, *args, **kwargs):
        
        import requests
        auth1 = self.generate_auth()
        return requests.Session(*args, auth=auth1, **kwargs)
1069383
def post_with_auth(path, response_class, payload)
      response_class.new(client.post_with_auth(path, payload))
    end
838455
def get(self, path):
        
        # Generate token
        service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
                                   gssapi.NameType.hostbased_service)
        ctx = gssapi.SecurityContext(usage="initiate", name=service_name)
        data = b64encode(ctx.step()).decode()

        # Make the connection
        connection = httplib.HTTPSConnection(self.url.netloc, 443)
        log.debug("GET {0}".format(path))
        connection.putrequest("GET", path)
        connection.putheader("Authorization", "Negotiate {0}".format(data))
        connection.putheader("Referer", self.url_string)
        connection.endheaders()

        # Perform the request, convert response into lines
        response = connection.getresponse()
        if response.status != 200:
            raise ReportError(
                "Failed to fetch tickets: {0}".format(response.status))
        lines = response.read().decode("utf8").strip().split("\n")[1:]
        log.debug("Tickets fetched:")
        log.debug(pretty(lines))
        return lines
739289
def _get_at_from_session(self):
        
        try:
            return self.request.session['oauth_%s_access_token'
                                        % get_token_prefix(
                                            self.request_token_url)]
        except KeyError:
            raise OAuthError(
                _('No access token saved for "%s".')
                % get_token_prefix(self.request_token_url))
76231
def get_session_token(self):
        '''  '''
        # HTTP POST query to session authenticate API
        try:
            response = requests.post(self.__session_url__ + 'sessionauth/v1/authenticate',
                                     cert=(self.__crt__, self.__key__), verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            raise
        if response.status_code == 200:
            # load json response as list
            data = json.loads(response.text)
            self.logger.debug(data)
            # grab token from list
            session_token = data['token']
        else:
            raise Exception('BAD HTTP STATUS: %s' % str(response.status_code))
        # return the token
        self.logger.debug(session_token)
        return session_token
1068322
def request_token(self):
        
        client = OAuth1(
            client_key=self._server_cache[self.client.server].key,
            client_secret=self._server_cache[self.client.server].secret,
            callback_uri=self.callback,
        )

        request = {"auth": client}
        response = self._requester(
            requests.post,
            "oauth/request_token",
            **request
        )

        data = parse.parse_qs(response.text)
        data = {
            'token': data[self.PARAM_TOKEN][0],
            'token_secret': data[self.PARAM_TOKEN_SECRET][0]
        }

        return data
529195
def _get_oauth_token(self):
        
        url = urljoin(self.api_url, '/oauth2/token')

        oauth = OAuth2Session(
            client_id=self._client_id,
            redirect_uri=config.REDIRECT_URI,
        )

        token = oauth.fetch_token(
            token_url=url,
            code=self._auth_code,
            client_secret=self._client_secret,
        )

        return token
241174
def _get_token_create_url(config):
    '''
    
    '''
    role_name = config.get('role_name', None)
    auth_path = '/v1/auth/token/create'
    base_url = config['url']
    return '/'.join(x.strip('/') for x in (base_url, auth_path, role_name) if x)
774993
def oauth_session(request, state=None, token=None):
    
    if settings.DISCORD_REDIRECT_URI is not None:
        redirect_uri = settings.DISCORD_REDIRECT_URI
    else:
        redirect_uri = request.build_absolute_uri(
            reverse('discord_bind_callback'))
    scope = (['email', 'guilds.join'] if settings.DISCORD_EMAIL_SCOPE
             else ['identity', 'guilds.join'])
    return OAuth2Session(settings.DISCORD_CLIENT_ID,
                         redirect_uri=redirect_uri,
                         scope=scope,
                         token=token,
                         state=state)
362363
def get(self, path, params=None):
        
        api_url = self.api_base_url + path

        headers = None
        try:
            headers = {
                "Authorization": 'Bearer {}'.format(settings.WP_API_AUTH_TOKEN)
            }
        except AttributeError:
            if self.first_get:
                logger.warning("WP_API_AUTH_TOKEN not found in settings. Only public APIs are available.")

        self.first_get = False

        return requests.get(api_url, headers=headers, params=params)