当前位置: 首页>>代码示例>>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;未经允许,请勿转载。