Python requests ошибка 401

You could have wrapped this in a function and used a decorator to evaluate the response and retry the auth on 401. Then you only need to decorate any function that requires this re-auth logic….

Update:
As requested, a code example. I’m afraid this one is an old piece of code, Python 2 based, but you’ll get the idea. This one will retry an http call a number of times as defined in settings.NUM_PLATFORM_RETRIES and will call a refresh_token on auth failures. you can adjust the use case and result to whatever.
You can then use this decorator around methods:

@retry_on_read_error
def some_func():
   do_something()



def retry_on_read_error(fn):
    """
    Retry Feed reads on failures
    If a token refresh is required it is performed before retry.
    This decorator relies on the model to have a refresh_token method defined, othewise it will fail
    """
    @wraps(fn)
    def _wrapper(self, *args, **kwargs):
        for i in range(settings.NUM_PLATFORM_RETRIES):
            try:
                res = fn(self, *args, **kwargs)

                try:
                    _res = json.loads(res)
                except ValueError:
                    # not a json response (could be local file read or non json data)
                    return res

                if 'error' in _res and _res['error']['status'] in (401, 400):
                    raise AccessRefusedException(_res['error']['message'])

                return res
            except (urllib2.URLError, IOError, AccessRefusedException) as e:
                if isinstance(e, AccessRefusedException):
                    self.refresh_token()
                continue
        raise ApiRequestFailed(
            "Api failing, after %s retries: %s" % (settings.NUM_PLATFORM_RETRIES, e), args, kwargs
        )

    return _wrapper

Answer by Bryson Massey

Why were the Apollo 12 astronauts tasked with bringing back part of the Surveyor 3 probe?

,

Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers

,Thanks for contributing an answer to Stack Overflow!,

Shift to remote work prompted more cybersecurity questions than any breach

It doesn’t get any less ugly than this, I think:

import requests
from requests.auth import HTTPBasicAuth

response = requests.get('http://your_url')

if response.status_code == 401:    
    response = requests.get('http://your_url', auth=HTTPBasicAuth('user', 'pass'))

if response.status_code != 200:
    # Definitely something's wrong

Answer by Aisha Berger

Getting 401 unauthorized error python after trying everything,Hi All, please help. I tried everything still getting 401 unauthorized error in python. Below is my code.,because I do know little bit of scraping and when trying with Selenium and BeautifulSoup (after opening the URL) it still gives me 401 unauthorized error.,Please help. I am exhausted trying every page on this community and you tube videos, nothing is working :(

Hi All, please help. I tried everything still getting 401 unauthorized error in python. Below is my code.

url = 'https://jira.mycompanyname.org/rest/api/2/issue/XYZ-85'server = 'https://jira.mycompanyname.org'headers = {'Accept':'application/json','Content-Type':'application/json','Authorization': 'Basic [base64 encoded string of my office email id:auth token]'}options = {'server':sever}query = {'jql':'project=XYZ'}response = requests.get(url,headers=headers,params=query)print(response.text)

Answer by Molly Velasquez

The 401 Error in Chrome,The 401 status code in the developer console in Chrome,The Internet Engineering Task Force (IETF) defines the error 401 Unauthorized as:,If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.

Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.

To do this in Windows, click on the Start button and type cmd into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns, and then hit Enter again:

cmd

Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.

To do this in Windows, click on the Start button and type cmd into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns, and then hit Enter again:

ipconfig/flushdns

Answer by Evelyn Baker

What I want to do is GET from a site and if that request returns a 401, then redo my authentication wiggle (which may be out of date) and try again. But I don’t want to try a third time, since that would be my authentication wiggle having the wrong credentials. Does anyone have a nice way of doing this that doesn’t involve properly ugly code, ideally in python requests library, but I don’t mind changing.,Consider returning an http status of 401, and a JSON object detailing the reason. If you’re using jQuery, that’ll drop you to the error() callback, which you can then parse your object.,I’m not familiar with PHP anymore, but this should work for just about any environment. You may have to suppress any automatic login form redirection though. In asp.net mvc the framework will see the 401 and push the default login form back, with a status of 200.,The above code will attempt to send all the POST requests at once. Despite the intention, it will be throttled by aiohttp.ClientSession’s TCP connector which allows a maximum of 100 simultaneous connections by default. To increase or remove this limitation, you must set a custom connector on the session.

It doesn’t get any less ugly than this, I think:

import requests
from requests.auth import HTTPBasicAuth

response = requests.get('http://your_url')

if response.status_code == 401:    
    response = requests.get('http://your_url', auth=HTTPBasicAuth('user', 'pass'))

if response.status_code != 200:
    # Definitely something's wrong

Answer by Veronica Beard

I get the exact same error when I try calling the Payment Processing Authorization endpoint.,Whenever I try to authenticate with Two Way SSL, I keep getting Error 401 code 9124. ,Using SoapUI, you can find the x-correlation-id in the Raw Tab of the response header.,I solved this by generating and importing my own CSR and private key.. I have still do not know why I could not get the auto generated own to work though.

[fedora@temp visa]$ python3 hello_world.py
< GET /vdp/helloworld HTTP/1.1
< Host: sandbox.api.visa.com
< User-Agent: python-requests/2.19.1
< Accept-Encoding: gzip, deflate
< Accept: application/json
< Connection: keep-alive
< Content-Type: application/json
< Authorization: Basic NDhHVU8wV1dPVTRNRVBWWElJSDUyMTFvYTdVOFFtOTNMQlRxODk5N0JkUVY2ZVZZNDo3MUpuVWhLdjN6V0FMT2o=
<

> HTTP/1.1 401 Unauthorized
> Server: nginx
> Content-Type: application/json;charset=UTF-8
> Content-Length: 119
> X-SERVED-BY: l73c018
> X-CORRELATION-ID: 1560548141_524_207894318_l73c018_VDP_WS
> x-vdp-normalized-url: /vdp/helloworld
> X-APP-STATUS: 401
> x-vdp-authn-api-visa-id: HELLOWORLD
> X-Frame-Options: SAMEORIGIN
> X-XSS-Protection: 1; mode=block
> X-Content-Type-Options: nosniff
> Strict-Transport-Security: max-age=2592000;includeSubdomains
> Cache-Control: no-cache, no-store, must-revalidate
> Pragma: no-cache
> Expires: -1
> Date: Fri, 14 Jun 2019 21:35:41 GMT
> Connection: keep-alive
>
{"responseStatus":{"status":401,"code":"9124","severity":"ERROR","message":"Incorrect credentials supplied","info":""}}
{'responseStatus': {'status': 401, 'code': '9124', 'severity': 'ERROR', 'message': 'Incorrect credentials supplied', 'info': ''}}
#!/usr/bin/python3

import requests
from requests_toolbelt.utils import dump

def main():

    URL = "<a href="https://sandbox.api.visa.com/vdp/helloworld" target="_blank">https://sandbox.api.visa.com/vdp/helloworld</a>"
    CA_CERT = "/home/fedora/visa/DigiCertGlobalRootCA.pem"
    CLIENT_CERT = "/home/fedora/visa/client_cert_d2288d04-5699-47ff-8d89-54cf04ec4fca.pem"
    PRIVATE_KEY = "/home/fedora/visa/key_d2288d04-5699-47ff-8d89-54cf04ec4fca.pem"
    USER_ID = '48GUO0WWOU4MEPVXIIH5211oa7U8Qm93LBTq8997BdQV6eVY4'
    PASS = '71JnUhKv3zWALOj'

    HEADERS = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    r = requests.get(URL,
        verify = (CA_CERT),
            cert = (CLIENT_CERT, PRIVATE_KEY),
            headers = HEADERS,
            auth = (USER_ID, PASS))

    data = dump.dump_all(r)
    print(data.decode('utf-8'))

    print(r.json())


if __name__ == "__main__":
    main()
#!/usr/bin/python3

import requests
from requests_toolbelt.utils import dump

def main():

    URL = "<a href="https://sandbox.api.visa.com/acs/v1/payments/authorizations" target="_blank">https://sandbox.api.visa.com/acs/v1/payments/authorizations</a>"
    CA_CERT = "/home/fedora/visa/DigiCertGlobalRootCA.pem"
    CLIENT_CERT = "/home/fedora/visa/client_cert_d2288d04-5699-47ff-8d89-54cf04ec4fca.pem"
    PRIVATE_KEY = "/home/fedora/visa/key_d2288d04-5699-47ff-8d89-54cf04ec4fca.pem"
    USER_ID = "48GUO0WWOU4MEPVXIIH5211oa7U8Qm93LBTq8997BdQV6eVY4"
    PASS = "71JnUhKv3zWALOj"

    HEADERS = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    BODY = {
    "acctInfo": {
    "primryAcctNum": {
    "pan": "4111111111111111",
    "panExpDt": "2019-12"
    }
    },
    "cardAcceptr": {
    "clientId": "0123456789012345678901234567893"
    },
    "freeFormDescrptnData": "Freeformdata",
    "msgIdentfctn": {
    "correlatnId": "14bc567d90f23e56a8f045",
    "origId": "123451234567890"
    },
    "msgTransprtData": "TransportData",
    "transctn": {
    "eComData": {
    "digitalGoods": "true",
    "eciCd": "5",
    "xid": "EEC4567F90123A5678B0123EA67890D2345678FF"
    },
    "localDtTm": "2019-06-14T18:11:07",
    "partialAuthInd": "true",
    "posData": {
    "envrnmnt": "eCom",
    "panEntryMode": "OnFile",
    "panSrce": "VCIND"
    },
    "tranAmt": {
    "amt": "123.45",
    "numCurrCd": "840"
    },
    "tranDesc": "Transactiondescription"
    },
    "verfctnData": {
    "billngAddr": {
    "addrLn": "PO Box 12345",
    "postlCd": "12345"
    }
    },
    "riskAssessmntData": {
    "lowVlExmptn": "true",
    "traExmptn": "true",
    "trustdMerchntExmptn": "true",
    "scpExmptn": "true",
    "delgtdAthntctn": "true"
    }
    }

    r = requests.post(URL,
            verify = (CA_CERT),
                cert = (CLIENT_CERT, PRIVATE_KEY),
                headers = HEADERS,
                auth = (USER_ID, PASS),
                data = BODY)

    data = dump.dump_all(r)
    print(data.decode('utf-8'))


if __name__ == "__main__":
    main()

Currently trying to request a json using python but I keep getting a 401 error on response. When I use curl I receive the correct json data.

Curl I use:

curl -H "X-Samanage-Authorization: Bearer API_TOKEN" -H 'Accept: application/vnd.samanage.v2.1+json' -H 'Content-Type: application/json' -X GET https://api.samanage.com/incidents.json

Python that results in 401 error:

import json
import requests

response  = requests.get('https://api.samanage.com/incidents.json', headers={'X-Samanage-Authorization': 'API_TOKEN'})

print(response.status_code)

Nikos Tavoularis's user avatar

asked Jan 2, 2018 at 12:36

J Doe's user avatar

2

Depending on what you’re trying to do, your problem is probably that you are not specifying the type of your credentials.

Try doing :

import json
import requests

response  = requests.get('https://api.samanage.com/incidents.json', headers={'X-Samanage-Authorization': 'Bearer ' + API_TOKEN})

print(response.status_code)

Another case, your API_TOKEN is not the actual token if you have not made a mistake while typing your code back. You have a STRING API_TOKEN, but not the actual token.

answered Jan 2, 2018 at 12:44

IMCoins's user avatar

IMCoinsIMCoins

3,1591 gold badge10 silver badges25 bronze badges

1

Хочу получить данные с сайта (true или false) через запросы, а именно requests.get(‘ссылка на сайт’). Ответ приходит в виде <[Response 401]>. Я смотрел в интернете, но не понял, в основном там писали про HTTPBasicAuth (но посмотрев про это, я тоже не понял, откуда взять логин и пароль и для чего они нужны).

Как мне получить нормальный ответ, а не 401?


  • Вопрос задан

  • 1083 просмотра

Если запрашиваемая страница требует аутентификации, то в запрос нужно передать соответствующую информацию, чтобы запрос был авторизован. Скорее всего это cookie аутентификация, может быть и Basic, и какие либо другие.

Так же проблема может быть в том, что не передаются нужные заголовки запроса, тот же user-agent.

Смотрите, какой запрос отправляет браузер и повторяйте его через requests.

Без кода непонятно

Пригласить эксперта


  • Показать ещё
    Загружается…

21 сент. 2023, в 19:28

10000 руб./за проект

21 сент. 2023, в 19:06

11111 руб./за проект

21 сент. 2023, в 19:00

6000000 руб./за проект

Минуточку внимания

The urllib.error.HTTPError is a class in the Python urllib library that represents an HTTP error. An HTTPError is raised when an HTTP request returns a status code that represents an error, such as 4xx (client error) or 5xx (server error).

HTTPError Attributes

The urllib.error.HTTPError class has the following attributes:

  • code: The HTTP status code of the error.
  • reason: The human-readable reason phrase associated with the status code.
  • headers: The HTTP response headers for the request that caused the HTTPError.

What Causes HTTPError

Here are some common reasons why an HTTPError might be raised:

  • Invalid or malformed request URL.
  • Invalid or malformed request parameters or body.
  • Invalid or missing authentication credentials.
  • Server internal error or malfunction.
  • Server temporarily unavailable due to maintenance or overload.

Python HTTPError Examples

Here are a few examples of HTTP errors in Python:

404 Not Found


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/404')
except urllib.error.HTTPError as err:
    print(f'A HTTPError was thrown: {err.code} {err.reason}')

In the above example, an invalid URL is attempted to be opened using the urllib.request.urlopen() function. Running the above code raises an HTTPError with code 404:


A HTTPError was thrown: 404 NOT FOUND

400 Bad Request


import urllib.request

try:
    response = urllib.request.urlopen('http://httpbin.org/status/400')
except urllib.error.HTTPError as err:
    if err.code == 400:
        print('Bad request!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, a bad request is sent to the server. Running the above code raises a HTTPError with code 400:


Bad request!

401 Unauthorized


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/401')
except urllib.error.HTTPError as err:
    if err.code == 401:
        print('Unauthorized!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, a request is sent to the server with missing credentials. Running the above code raises a HTTPError with code 401:


Unauthorized!

500 Internal Server Error


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/500')
except urllib.error.HTTPError as err:
    if err.code == 500:
        print('Internal server error!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, the server experiences an error internally. Running the above code raises a HTTPError with code 500:


Internal server error!

How to Fix HTTPError in Python

To fix HTTP errors in Python, the following steps can be taken:

  1. Check the network connection and ensure it is stable and working.
  2. Check the URL being accessed and make sure it is correct and properly formatted.
  3. Check the request parameters and body to ensure they are valid and correct.
  4. Check whether the request requires authentication credentials and make sure they are included in the request and are correct.
  5. If the request and URL are correct, check the HTTP status code and reason returned in the error message. This can give more information about the error.
  6. Try adding error handling code for the specific error. For example, the request can be attempted again or missing parameters can be added to the request.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Понравилась статья? Поделить с друзьями:
  • Python39 dll ошибка
  • Python requests обработка ошибок
  • Python27 dll ошибка
  • Python requests коды ошибок
  • Python трассировка ошибки