當前位置: 首頁>>代碼示例>>Python>>正文


Python oauth1.Client方法代碼示例

本文整理匯總了Python中oauthlib.oauth1.Client方法的典型用法代碼示例。如果您正苦於以下問題:Python oauth1.Client方法的具體用法?Python oauth1.Client怎麽用?Python oauth1.Client使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在oauthlib.oauth1的用法示例。


在下文中一共展示了oauth1.Client方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_create_auth

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def test_create_auth():
    """
    Verifies that the default Client is used
    when all the tokens are not empty strings.
    """
    api = Api("https://api.cardmarket.com/ws/v1.1/output.json")
    auth = api.create_auth(
        "https://api.cardmarket.com/ws/v1.1/output.json",
        app_token="app_token",
        app_secret="app_secret",
        access_token="access_token",
        access_token_secret="access_token_secret",
    )

    assert isinstance(auth.client, Client)
    assert auth.client.client_key == "app_token"
    assert auth.client.client_secret == "app_secret"
    assert auth.client.resource_owner_key == "access_token"
    assert auth.client.resource_owner_secret == "access_token_secret" 
開發者ID:evonove,項目名稱:mkm-sdk,代碼行數:21,代碼來源:test_api.py

示例2: sign_request

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def sign_request(self, url, method, body, headers):
        """Sign a request.

        :param url: The URL to which the request is to be sent.
        :param headers: The headers in the request. These will be updated with
            the signature.
        """
        # The use of PLAINTEXT here was copied from MAAS, but we should switch
        # to HMAC once it works server-side.
        client = oauth1.Client(
            self.consumer_key,
            self.consumer_secret,
            self.token_key,
            self.token_secret,
            signature_method=oauth1.SIGNATURE_PLAINTEXT,
            realm=self.realm,
        )
        # To preserve API backward compatibility convert an empty string body
        # to `None`. The old "oauth" library would treat the empty string as
        # "no body", but "oauthlib" requires `None`.
        body = None if body is None or len(body) == 0 else body
        uri, signed_headers, body = client.sign(url, method, body, headers)
        headers.update(signed_headers) 
開發者ID:maas,項目名稱:python-libmaas,代碼行數:25,代碼來源:__init__.py

示例3: __init__

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def __init__(self, apikey):
        self.consumer_key, self.token_key, self.token_secret = apikey.split(
            ':')
        self.consumer_secret = ""
        self.realm = "OAuth"

        self.oauth_client = oauth1.Client(
            self.consumer_key,
            self.consumer_secret,
            self.token_key,
            self.token_secret,
            signature_method=oauth1.SIGNATURE_PLAINTEXT,
            realm=self.realm) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:15,代碼來源:api_client.py

示例4: create_client

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def create_client(self, **kwargs):
        return Client(
            self.consumer_key,
            signature_method=SIGNATURE_RSA,
            rsa_key=self.rsa_key,
            **kwargs
        ) 
開發者ID:spoqa,項目名稱:geofront,代碼行數:9,代碼來源:stash.py

示例5: get_oauth_request_signature

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def get_oauth_request_signature(key, secret, url, headers, body):
    """
    Returns Authorization header for a signed oauth request.

    Arguments:
        key (str): LTI provider key
        secret (str): LTI provider secret
        url (str): URL for the signed request
        header (str): HTTP headers for the signed request
        body (str): Body of the signed request

    Returns:
        str: Authorization header for the OAuth signed request
    """
    client = oauth1.Client(client_key=str(key), client_secret=str(secret))
    try:
        # Add Authorization header which looks like:
        # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
        # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
        # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
        _, headers, _ = client.sign(
            str(url.strip()),
            http_method=u'POST',
            body=body,
            headers=headers
        )
    except ValueError:  # Scheme not in url.
        raise Lti1p1Error("Failed to sign oauth request")

    return headers['Authorization'] 
開發者ID:edx,項目名稱:xblock-lti-consumer,代碼行數:32,代碼來源:oauth.py

示例6: log_authorization_header

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def log_authorization_header(request, client_key, client_secret):
    """
    Helper function that logs proper HTTP Authorization header for a given request

    Used only in debug situations, this logs the correct Authorization header based on
    the request header and body according to OAuth 1 Body signing

    Arguments:
        request (webob.Request):  Request object to log Authorization header for

    Returns:
        nothing
    """
    sha1 = hashlib.sha1()
    sha1.update(request.body)
    oauth_body_hash = str(base64.b64encode(sha1.digest()))  # pylint: disable=too-many-function-args
    log.debug("[LTI] oauth_body_hash = %s", oauth_body_hash)
    client = oauth1.Client(client_key, client_secret)
    params = client.get_oauth_params(request)
    params.append((u'oauth_body_hash', oauth_body_hash))
    mock_request = SignedRequest(
        uri=str(urllib.parse.unquote(request.url)),
        headers=request.headers,
        body=u"",
        decoded_body=u"",
        oauth_params=params,
        http_method=str(request.method),
    )
    sig = client.get_oauth_signature(mock_request)
    mock_request.oauth_params.append((u'oauth_signature', sig))

    __, headers, _ = client._render(mock_request)  # pylint: disable=protected-access
    log.debug(
        "\n\n#### COPY AND PASTE AUTHORIZATION HEADER ####\n%s\n####################################\n\n",
        headers['Authorization']
    ) 
開發者ID:edx,項目名稱:xblock-lti-consumer,代碼行數:38,代碼來源:oauth.py

示例7: _get_oauth_headers

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def _get_oauth_headers(self, url):
        LOG.debug("Getting authorization headers for %s.", url)
        client = oauth1.Client(
            CONF.maas.oauth_consumer_key,
            client_secret=CONF.maas.oauth_consumer_secret,
            resource_owner_key=CONF.maas.oauth_token_key,
            resource_owner_secret=CONF.maas.oauth_token_secret,
            signature_method=oauth1.SIGNATURE_PLAINTEXT)
        realm = _Realm("")
        headers = client.sign(url, realm=realm)[1]
        return headers 
開發者ID:cloudbase,項目名稱:cloudbase-init,代碼行數:13,代碼來源:maasservice.py

示例8: oauth_headers

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def oauth_headers(
    url, consumer_key, token_key, token_secret, consumer_secret, clockskew=0
):
    """Build OAuth headers using given credentials."""
    timestamp = int(time.time()) + clockskew
    client = oauth.Client(
        consumer_key,
        client_secret=consumer_secret,
        resource_owner_key=token_key,
        resource_owner_secret=token_secret,
        signature_method=oauth.SIGNATURE_PLAINTEXT,
        timestamp=str(timestamp),
    )
    uri, signed_headers, body = client.sign(url)
    return signed_headers 
開發者ID:maas,項目名稱:maas,代碼行數:17,代碼來源:maas_api_helper.py

示例9: sign_request

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def sign_request(self, url, headers):
        """Sign a request.

        @param url: The URL to which the request is to be sent.
        @param headers: The headers in the request.  These will be updated
            with the signature.
        """
        client = oauth1.Client(
            self._consumer_key,
            resource_owner_key=self._resource_token,
            resource_owner_secret=self._resource_secret,
            signature_method=oauth1.SIGNATURE_PLAINTEXT,
        )
        _, signed_headers, _ = client.sign(url)
        headers.update(signed_headers) 
開發者ID:maas,項目名稱:maas,代碼行數:17,代碼來源:maas_client.py

示例10: test_lti_request_body

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def test_lti_request_body(self):
        """Simulate an LTI launch request with oauth in the body.

        This test uses the oauthlib library to simulate an LTI launch request and make sure
        that our LTI verification works.
        """
        passport = ConsumerSiteLTIPassportFactory(consumer_site__domain="testserver")
        lti_parameters = {
            "resource_link_id": "df7",
            "context_id": "course-v1:ufr+mathematics+0001",
            "roles": "Instructor",
        }
        resource_id = uuid.uuid4()
        url = "http://testserver/lti/videos/{!s}".format(resource_id)
        client = oauth1.Client(
            client_key=passport.oauth_consumer_key, client_secret=passport.shared_secret
        )
        # Compute Authorization header which looks like:
        # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
        # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
        # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
        _uri, headers, _body = client.sign(
            url,
            http_method="POST",
            body=lti_parameters,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )

        # Parse headers to pass to template as part of context:
        oauth_dict = dict(
            param.strip().replace('"', "").split("=")
            for param in headers["Authorization"].split(",")
        )

        signature = oauth_dict["oauth_signature"]
        oauth_dict["oauth_signature"] = unquote(signature)
        oauth_dict["oauth_nonce"] = oauth_dict.pop("OAuth oauth_nonce")

        lti_parameters.update(oauth_dict)
        request = self.factory.post(
            url, lti_parameters, HTTP_REFERER="https://testserver"
        )
        lti = LTI(request, uuid.uuid4())
        self.assertTrue(lti.verify())
        self.assertEqual(lti.get_consumer_site(), passport.consumer_site)

        # If we alter the signature (e.g. add "a" to it), the verification should fail
        oauth_dict["oauth_signature"] = "{:s}a".format(signature)

        lti_parameters.update(oauth_dict)
        request = self.factory.post(url, lti_parameters)
        lti = LTI(request, resource_id)
        with self.assertRaises(LTIException):
            lti.verify() 
開發者ID:openfun,項目名稱:marsha,代碼行數:56,代碼來源:test_lti.py

示例11: test_lti_request_body_without_referer

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def test_lti_request_body_without_referer(self):
        """Simulate an LTI launch request with oauth in the body.

        When the http referer is missing the request should still be authorized.
        """
        passport = ConsumerSiteLTIPassportFactory(consumer_site__domain="testserver")
        lti_parameters = {
            "resource_link_id": "df7",
            "context_id": "course-v1:ufr+mathematics+0001",
            "roles": "Instructor",
        }
        resource_id = uuid.uuid4()
        url = "http://testserver/lti/videos/{!s}".format(resource_id)
        client = oauth1.Client(
            client_key=passport.oauth_consumer_key, client_secret=passport.shared_secret
        )
        # Compute Authorization header which looks like:
        # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
        # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
        # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
        _uri, headers, _body = client.sign(
            url,
            http_method="POST",
            body=lti_parameters,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )

        # Parse headers to pass to template as part of context:
        oauth_dict = dict(
            param.strip().replace('"', "").split("=")
            for param in headers["Authorization"].split(",")
        )

        signature = oauth_dict["oauth_signature"]
        oauth_dict["oauth_signature"] = unquote(signature)
        oauth_dict["oauth_nonce"] = oauth_dict.pop("OAuth oauth_nonce")

        lti_parameters.update(oauth_dict)
        request = self.factory.post(url, lti_parameters)
        lti = LTI(request, uuid.uuid4())
        self.assertTrue(lti.verify())
        self.assertEqual(lti.get_consumer_site(), passport.consumer_site)

        # If we alter the signature (e.g. add "a" to it), the verification should fail
        oauth_dict["oauth_signature"] = "{:s}a".format(signature)

        lti_parameters.update(oauth_dict)
        request = self.factory.post(url, lti_parameters)
        lti = LTI(request, resource_id)
        with self.assertRaises(LTIException):
            lti.verify() 
開發者ID:openfun,項目名稱:marsha,代碼行數:53,代碼來源:test_lti.py

示例12: fetch_from_twitter

# 需要導入模塊: from oauthlib import oauth1 [as 別名]
# 或者: from oauthlib.oauth1 import Client [as 別名]
def fetch_from_twitter(
    credentials,
    path,
    params: List[Tuple[str, str]],
    since_id: Optional[int],
    per_page: int,
    n_pages: int,
) -> List[Dict[str, Any]]:
    oauth_client = oauth1.Client(
        client_key=credentials["consumer_key"],
        client_secret=credentials["consumer_secret"],
        resource_owner_key=credentials["resource_owner_key"],
        resource_owner_secret=credentials["resource_owner_secret"],
    )

    page_dataframes = [create_empty_table()]

    max_id = None
    async with aiohttp.ClientSession() as session:  # aiohttp timeout of 5min
        for page in range(n_pages):
            # Assume {path} contains '?' already
            page_params = [
                *params,
                ("tweet_mode", "extended"),
                ("count", str(per_page)),
            ]
            if since_id:
                page_params.append(("since_id", str(since_id)))
            if max_id:
                page_params.append(("max_id", str(max_id)))

            page_url = f"https://api.twitter.com/1.1/{path}?{urlencode(page_params)}"

            page_url, headers, body = oauth_client.sign(
                page_url, headers={"Accept": "application/json"}
            )

            # aiohttp internally performs URL canonization before sending
            # request. DISABLE THIS: it rewrites the signed URL!
            #
            # https://github.com/aio-libs/aiohttp/issues/3424
            page_url = yarl.URL(page_url, encoded=True)  # disable magic

            response = await session.get(page_url, headers=headers)
            response.raise_for_status()
            page_statuses = await response.json()

            if isinstance(page_statuses, dict) and "statuses" in page_statuses:
                # /search wraps result in {}
                page_statuses = page_statuses["statuses"]

            if not page_statuses:
                break

            # Parse one page at a time, instead of parsing all at the end.
            # Should save a bit of memory and make a smaller CPU-blip in our
            # event loop.
            page_dataframes.append(statuses_to_dataframe(page_statuses))
            max_id = page_statuses[-1]["id"] - 1

    return pd.concat(page_dataframes, ignore_index=True, sort=False) 
開發者ID:CJWorkbench,項目名稱:cjworkbench,代碼行數:63,代碼來源:twitter.py


注:本文中的oauthlib.oauth1.Client方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。