URL авторизации Upwork API возвращает «Unauthorized» несмотря на то, что ключ API активен - PullRequest
0 голосов
/ 15 января 2020

Я пытаюсь подключиться к Upwork API с помощью клиента Python.

Мой тип проекта - «рабочий стол», ключ - «активный».

Однако URL-адрес аутентификации возвращает 403 и в браузере выводит сообщение «Несанкционировано».

enter image description here

Вот код, который просто пытается воссоздать шаги в Документация API .

import upwork
import requests

public_key = ''
secret_key = ''

client = upwork.Client(public_key, secret_key)
authorize_url = client.auth.get_authorize_url()

requests.get(authorize_url)

Я также прочитал эту другую проблему , где сопровождающий (?) не рекомендует использовать Python 3. Однако, как я Если вы хотите использовать pandas с данными, извлеченными из API, мне нужно положиться на него.

В OP той же проблемы упоминается решение проблемы с пакетом requests_oauthlib. Ниже приведена моя попытка создать соединение, но оно тоже не удается.

from requests_oauthlib import OAuth1Session

oauth = OAuth1Session(public_key, secret_key)
fetch_response = oauth.fetch_request_token(authorize_url)

Вот результат трассировки от использования requests_oauthlib. В нем упоминается, что они считают, что я «использую средства автоматизации для просмотра веб-сайта».

---------------------------------------------------------------------------
TokenRequestDenied                        Traceback (most recent call last)
<ipython-input-10-e7e19b178437> in <module>
      1 from requests_oauthlib import OAuth1Session, OAuth1
      2 oauth = OAuth1Session(public_key, secret_key)
----> 3 fetch_response = oauth.fetch_request_token(authorize_url)
      4 # fetch_response

~/anaconda3/envs/upwork/lib/python3.7/site-packages/requests_oauthlib/oauth1_session.py in fetch_request_token(self, url, realm, **request_kwargs)
    285         """
    286         self._client.client.realm = " ".join(realm) if realm else None
--> 287         token = self._fetch_token(url, **request_kwargs)
    288         log.debug("Resetting callback_uri and realm (not needed in next phase).")
    289         self._client.client.callback_uri = None

~/anaconda3/envs/upwork/lib/python3.7/site-packages/requests_oauthlib/oauth1_session.py in _fetch_token(self, url, **request_kwargs)
    367         if r.status_code >= 400:
    368             error = "Token request failed with code %s, response was '%s'."
--> 369             raise TokenRequestDenied(error % (r.status_code, r.text), r)
    370 
    371         log.debug('Decoding token from response "%s"', r.text)

TokenRequestDenied: Token request failed with code 403, response was '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Access to this page has been denied.</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300" rel="stylesheet">
    <style>
        html, body {
            margin: 0;
            padding: 0;
            font-family: 'Open Sans', sans-serif;
            color: #000;
        }

        a {
            color: #c5c5c5;
            text-decoration: none;
        }

        .container {
            align-items: center;
            display: flex;
            flex: 1;
            justify-content: space-between;
            flex-direction: column;
            height: 100%;
        }

        .container > div {
            width: 100%;
            display: flex;
            justify-content: center;
        }

        .container > div > div {
            display: flex;
            width: 80%;
        }

        .customer-logo-wrapper {
            padding-top: 2rem;
            flex-grow: 0;
            background-color: #fff;
            visibility: hidden;
        }

        .customer-logo {
            border-bottom: 1px solid #000;
        }

        .customer-logo > img {
            padding-bottom: 1rem;
            max-height: 50px;
            max-width: 100%;
        }

        .page-title-wrapper {
            flex-grow: 2;
        }

        .page-title {
            flex-direction: column-reverse;
        }

        .content-wrapper {
            flex-grow: 5;
        }

        .content {
            flex-direction: column;
        }

        .page-footer-wrapper {
            align-items: center;
            flex-grow: 0.2;
            background-color: #000;
            color: #c5c5c5;
            font-size: 70%;
        }

        @media (min-width: 768px) {
            html, body {
                height: 100%;
            }
        }
    </style>
    <!-- Custom CSS -->
</head>

<body>
<section class="container">
    <div class="customer-logo-wrapper">
        <div class="customer-logo">
            <img src="" alt="Logo"/>
        </div>
    </div>
    <div class="page-title-wrapper">
        <div class="page-title">
            <h1>Please verify you are a human</h1>
        </div>
    </div>
    <div class="content-wrapper">
        <div class="content">
            <div id="px-captcha">
            </div>
            <p>
                Access to this page has been denied because we believe you are using automation tools to browse the
                website.
            </p>
            <p>
                This may happen as a result of the following:
            </p>
            <ul>
                <li>
                    Javascript is disabled or blocked by an extension (ad blockers for example)
                </li>
                <li>
                    Your browser does not support cookies
                </li>
            </ul>
            <p>
                Please make sure that Javascript and cookies are enabled on your browser and that you are not blocking
                them from loading.
            </p>
            <p>
                Reference ID: #fe0d4e60-37b3-11ea-a803-55cc905cdf7a
            </p>
        </div>
    </div>
    <div class="page-footer-wrapper">
        <div class="page-footer">
            <p>
                Powered by
                <a href="https://www.perimeterx.com/whywasiblocked">PerimeterX</a>
                , Inc.
            </p>
        </div>
    </div>
</section>
<!-- Px -->
<script>
    window._pxAppId = 'PXSs13U803';
    window._pxJsClientSrc = '/Ss13U803/init.js';
    window._pxFirstPartyEnabled = true;
    window._pxVid = '';
    window._pxUuid = 'fe0d4e60-37b3-11ea-a803-55cc905cdf7a';
    window._pxHostUrl = '/Ss13U803/xhr';
</script>
<!-- Captcha -->
<script>
    var s = document.createElement('script');
    s.src = '/Ss13U803/captcha/PXSs13U803/captcha.js?a=c&m=0&u=fe0d4e60-37b3-11ea-a803-55cc905cdf7a&v=';
    var p = document.getElementsByTagName('head')[0];
    p.insertBefore(s, null);
    if (true) {
        s.onerror = function () {
            s = document.createElement('script');
            var suffixIndex = '/Ss13U803/captcha/PXSs13U803/captcha.js?a=c&m=0&u=fe0d4e60-37b3-11ea-a803-55cc905cdf7a&v='.indexOf('captcha.js');
            var temperedBlockScript = '/Ss13U803/captcha/PXSs13U803/captcha.js?a=c&m=0&u=fe0d4e60-37b3-11ea-a803-55cc905cdf7a&v='.substring(suffixIndex);
            s.src = '//captcha.px-cdn.net/PXSs13U803/' + temperedBlockScript;
            p.parentNode.insertBefore(s, p);
        };
    }
</script>
<!-- Custom Script -->
</body>
</html>

'.

Есть какие-нибудь подсказки, как мне решить эту проблему?

1 Ответ

0 голосов
/ 17 января 2020

Причиной появления сообщения «Неавторизованный» является неверный токен запроса в URL-адресе - «Нет» в URL-адресе на снимке экрана.

Если вы используете оболочку или что-то подобное, убедитесь, что вы создали действительный URL авторизации и используйте токен вместо пустого / неопределенного значения

...