Maximum of api retries exceeded как исправить

Сталкиваюсь не первый раз с этой проблемой, закрывал глаза, но сейчас хочу решить эту проблему.
При старте бота изредка выскакивает ошибка, или в работе бота. Выдает ошибку и на vds и на локалке.

Traceback (most recent call last):
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3utilconnection.py", line 57, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsocket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11002] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connectionpool.py", line 343, in _make_request
    self._validate_conn(conn)
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connectionpool.py", line 839, in _validate_conn
    conn.connect()
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connection.py", line 301, in connect
    conn = self._new_conn()
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connection.py", line 168, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x04EAD110>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesrequestsadapters.py", line 449, in send
    timeout=timeout
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesurllib3utilretry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.vk.com', port=443): Max retries exceeded with url: /method/stats.trackVisitor (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x04EAD110>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Bogdan/PycharmProjects/?/---.py", line 1, in <module>
    from --- import *
  File "C:UsersBogdanPycharmProjects?---.py", line 24, in <module>
    from --- import *
  File "C:UsersBogdanPycharmProjects?---.py", line 122, in <module>
    vk._auth_token()
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesvk_apivk_api.py", line 209, in _auth_token
    if not reauth and self._check_token():
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesvk_apivk_api.py", line 501, in _check_token
    self.method('stats.trackVisitor')
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesvk_apivk_api.py", line 602, in method
    values
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesrequestssessions.py", line 581, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesrequestssessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesrequestssessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:UsersBogdanAppDataLocalProgramsPythonPython37-32libsite-packagesrequestsadapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.vk.com', port=443): Max retries exceeded with url: /method/stats.trackVisitor (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x04EAD110>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

Python is a simple, minimalistic, and easy-to-comprehend programming language that is globally-accepted and universally-used today. Its simple, easy-to-learn syntax can sometimes lead Python developers – especially those who are newer to the language – into missing some of its subtleties and underestimating the power of the diverse Python language.

One of the most popular error messages that new developers encounter when using requests library in Python is the “Max retries exceeded with URL” (besides timeout errors). While it seems simple, sometimes this somewhat vague error message can make even advanced Python developers scratching their head for a few good hours.

This article will show you what causes “Max retries exceeded with URL” error and a few ways to debug it.

Max retries exceeded with URL is a common error, you will encounter it when using requests library to make a request. The error indicates that the request cannot be made successfully. Usually, the verbose error message should look like the output below

Traceback (most recent call last):
  File "/home/nl/example.py", line 17, in <module>
    page1 = requests.get(ap)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 383, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 486, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 378, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='localhost.com', port=443): Max retries exceeded with url: /api (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)Code language: JavaScript (javascript)

Sometimes, the error message may look slightly different, like below :

requests.exceptions.ConnectionError(MaxRetryError("HTTPSConnectionPool(host='api.example.com', port=443): 
    Max retries exceeded with url: /api.json (
    Caused by <class 'socket.error'>: [Errno 10054] 
    An existing connection was forcibly closed by the remote host)",),)Code language: HTML, XML (xml)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8001): Max retries exceeded with url: /api (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10f96ecc0>: Failed to establish a new connection: [Errno 61] Connection refused'))Code language: JavaScript (javascript)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.example.com', port=80): Max retries exceeded with url: /api (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000008EC69AAA90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))Code language: JavaScript (javascript)
requests.exceptions.SSLError: HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: /api (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)')))Code language: JavaScript (javascript)

The error message usually begins with requests.exceptions.ConnectionError, which tell us that there is something bad happened when requests was trying to connect. Sometimes, the exception is requests.exceptions.SSLError which is obviously a SSL-related problem.

The exception then followed by a more detailed string about the error, which could be Failed to establish a new connection: [Errno 61] Connection refused, [Errno 11001] getaddrinfo failed, [Errno 10054] An existing connection was forcibly closed by the remote host or [Errno -2] Name or service not known. These messages were produced by the underlying system library which requests called internally. Based on these texts, we can further isolate and fix the problems.

Double-check the URL

There are a possibility that your requested URL wrong. It may be malformed or leading to a non-existent endpoint. In reality, this is usually the case among Python beginners. Seasoned developers can also encounter this error, especially when the URL is parsed from a webpage, which can be a relative URL or schemeless URL.

One way to further debug this is to prepare the URL in advance, then print it before actually making a connection.

# ...
url = soup.find("#linkout").href
print(url) # prints out "/api" which is a non-valid URL
r = requests.get(url)Code language: PHP (php)

Unstable internet connection / server overload

The underlying problem may be related to your own connection or the server you’re trying to connect to. Unstable internet connection may cause packet loss between network hops, leading to unsuccessful connection. There are times the server has received so many requests that it cannot process them all, therefore your requests won’t receive a response.

In this case, you can try increasing retry attempts and disable keep-alive connections to see if the problems go away. The amount of time spent for each request will certainly increase too, but that’s a trade-off you must accept. Better yet, find a more reliable internet connection.

import requests
requests.adapters.DEFAULT_RETRIES = 5 # increase retries number
s = requests.session()
s.keep_alive = False # disable keep alive
s.get(url)Code language: PHP (php)

Increase request timeout

Another way that you can avoid “Max retries exceeded with URL” error, especially when the server is busy handling a huge number of connections, is to increase the amount of time requests library waits for a response from the server. In other words, you wait longer for a response, but increase the chance for a request to successfully finishes. This method can also be applied when the server is in a location far away from yours.

In order to increase request timeout, simply pass the time value in seconds to the get or post method :

r = requests.get(url, timeout=3)

You can also pass a tuple to timeout with the first element being a connect timeout (the time it allows for the client to establish a connection to the server), and the second being a read timeout (the time it will wait on a response once your client has established a connection).

If the request establishes a connection within 2 seconds and receives data within 5 seconds of the connection being established, then the response will be returned as it was before. If the request times out, then the function will raise a Timeout exception:

requests.get('https://api.github.com', timeout=(2, 5))Code language: JavaScript (javascript)

Apply backoff factor

backoff_factor is an urllib3 argument, the library which requests relies on to initialize a network connection. Below is an example where we use backoff_factor to slow down the requests to the servers whenever there’s a failed one.

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

session = requests.Session()
retry = Retry(connect=3, backoff_factor=1)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

session.get(url)Code language: JavaScript (javascript)

According to urllib3 documentation, backoff_factor is base value which the library use to calculate sleep interval between retries. Specifically, urllib3 will sleep for {backoff factor} * (2 ^ ({number of total retries} - 1)) seconds after every failed connection attempt.

For example, If the backoff_factor is 0.1, then sleep() will sleep for 0.0s, 0.2s, 0.4s, … between retries. By default, backoff is disabled (set to 0). It will also force a retry if the status code returned is 500, 502, 503 or 504.

You can customize Retry to have even more granular control over retries. Other notable options are:

  • total – Total number of retries to allow.
  • connect – How many connection-related errors to retry on.
  • read – How many times to retry on read errors.
  • redirect – How many redirects to perform.
  • _methodwhitelist – Set of uppercased HTTP method verbs that we should retry on.
  • _statusforcelist – A set of HTTP status codes that we should force a retry on.
  • _backofffactor – A backoff factor to apply between attempts.
  • _raise_onredirect – Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range.
  • raise_on_status – Similar meaning to _raise_onredirect: whether we should raise an exception, or return a response, if status falls in _statusforcelist range and retries have been exhausted.

We hope that the article helped you successfully debugged “Max retries exceeded with URL” error in Python requests library, as well as avoid encountering it in the future. We’ve also written a few other guides for fixing common Python errors, such as Timeout in Python requests, Python Unresolved Import in VSCode or “IndexError: List Index Out of Range” in Python. If you have any suggestion, please feel free to leave a comment below.

Hi guys, today i got this error:

File «/Library/Python/2.7/site-packages/binance/client.py», line 94, in init
self.ping()
File «/Library/Python/2.7/site-packages/binance/client.py», line 362, in ping
return self._get(‘ping’)
File «/Library/Python/2.7/site-packages/binance/client.py», line 206, in _get
return self._request_api(‘get’, path, signed, version, **kwargs)
File «/Library/Python/2.7/site-packages/binance/client.py», line 180, in _request_api
return self._request(method, uri, signed, **kwargs)
File «/Library/Python/2.7/site-packages/binance/client.py», line 174, in _request
response = getattr(self.session, method)(uri, **kwargs)
File «/Library/Python/2.7/site-packages/requests/sessions.py», line 521, in get
return self.request(‘GET’, url, **kwargs)
File «/Library/Python/2.7/site-packages/requests/sessions.py», line 508, in request
resp = self.send(prep, **send_kwargs)
File «/Library/Python/2.7/site-packages/requests/sessions.py», line 618, in send
r = adapter.send(request, **kwargs)
File «/Library/Python/2.7/site-packages/requests/adapters.py», line 506, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host=’api.binance.com’, port=443): Max retries exceeded with url: /api/v1/ping (Caused by SSLError(SSLError(1, u'[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)’),))

Any thoughts? Thank you.

The max retries exceeded with URL httpsconnectionpool code exception compromises your programming experience when the system fails to verify the SSL certificate.Max Retries Exceeded With URL

On the flip side, we experienced the max retries exceeded with curl localhost log with unstable internet connections, or the server was too busy, confusing the program or application.

Nevertheless, all culprits and confusing instances confirming the error log display similar messages and indicators. As a result, this profound debugging guide discusses several sophisticated approaches and solutions for the max retries exceeded with URL selenium Python that should help you overcome the broken warning.

Contents

  • When Does the Max Retries Exceeded With URL Error Happens? 2 Causes
    • – Getting Content From an Application With the Range Command
    • – Creating a Form With a Dropdown on API
  • How To Fix the Max Retries Exceeded With URL Code Exception?
    • – Introduce the Request Feature Calculating the Public IP Addresses
  • Conclusion

When Does the Max Retries Exceeded With URL Error Happens? 2 Causes

The max retries exceeded with URL odoo code exception happens when the system fails to verify the SSL certificate. In addition, we confirmed the max retries error log when sending browser requests with unstable internet connections or the server is too busy, causing unexpected obstacles.

For instance, the max retries exceeded with URL cannot connect to proxy messages are standard when your machine encounters SSL certificate obstacles or inconsistencies. As a result, the request library fails to implement the SSL certificate verification procedure to ensure your program or application uses a safe connection, confirming the max retries exceeded.

However, the bug’s culprit can sometimes be as simple as a typo in your URL, which rarely happens with advanced projects, but it is possible. This is why learning about the invalid syntax and script is as important as implementing the retries exceeded solutions to your documentation.

On the contrary, your internet connection is sometimes responsible for the python-requests max retries exceeded with URL newconnectionerror, especially when sending browser requests. This inconsistency forces your program to display several warnings and messages indicating the flawed processes, including the exceeded number of URL retries.

So, we will recreate the mistake using real-life examples and scripts before exemplifying the possible debugging methods. In addition, these chapters should help you troubleshoot your program and pinpoint the exact broken commands you must isolate when changing the inputs or properties.

– Getting Content From an Application With the Range Command

This article’s first broken instance attempts to get content from an application with the range command. Although this procedure is straightforward and works with most values, the script fails to interpret the inputs when the value exceeds 100.Max Retries Exceeded With URL Causes

To make things simple for you, we will provide the code snippet running all functions, and the error logs your system displays after launching the range function. These syntaxes indicate inconsistencies.

The following example provides the standard imported commands:

import requests

from lxml import html

page = requests.get (“https://itunes.apple.com/genre/ios-business/id6000?mt = 8”)

tree = html.fromstring (page.text)

flist = []

plist = []

for i in range (0, 100):

httpconnectionpool(host=’localhost’ port=8080) max retries exceeded with url

app = tree.xpath (“//div[@class=’column first’]/ul/li/ @href”)

ap = app [0]

page1 = requests.get (ap)

Although everything appears fully functional and the syntax is clean, your system confirms the flaws displaying an exception and halting further procedures. Still, you can use the error log to pinpoint the failed inputs.

You can learn more about the bug in the following example:

Traceback (most recent call last):

File “/home/preetham/Desktop/eg.py”, line 23, in <module>

page1 = requests.get(ap)

File “/usr/local/lib/python2.7/dist-packages/requests/api.py”, line 61, in get

return request (‘get’, url, **kwargs)

File “/usr/local/lib/python2.7/dist-packages/requests/api.py”, line 76, in request

return session.request (method = method, url = url, **kwargs)

File “/usr/local/lib/python2.7/dist-packages/requests/sessions.py”, line 268, in request

resp = self.send (prep, **send_kwargs)

File “/usr/local/lib/python2.7/dist-packages/requests/sessions.py”, line 579 in send

r = adapter.send (request, **kwargs)

File “/usr/local/lib/python2.7/dist-packages/requests/adapters.py”, line 612, in send

raise ConnectionError (e)

httpsconnectionpool(host=’pypi org port=443): max retries exceeded with url

requests.exceptions.ConnectionError: HTTPSConnectionPool (host = ‘itunes.apple.com’, port = 225):

Max retries exceeded with url: /in/app/id469337564?mt = 8

The last few code lines specify this error’s exact port and location, which is beneficial before working on your code.

– Creating a Form With a Dropdown on API

Creating a form with a dropdown on API is this article’s second and last broken procedure displaying the same code exception. Namely, this project has two applications managing the quotes and master data from the authors. As a result, we will exemplify the forms and serializers creating the models. In addition, we will provide the views to help you troubleshoot the program.

The following example provides the project’s main serializers:

from .models import Author

from rest_framework import serializers

class AuthorListSerializer (serializers.ModelSerializer):

class Meta:

model = Author

fields = [‘id’, ‘name’, ‘surname’]

This code snippet renders a few commands, which in theory, should be simple. However, the project is only complete after listing the forms and views.

You can learn about the form syntax in the following snippet:

from django import forms

from .models import Quote, Author, Source

from MyProject.api_calls import authorlist

class TestForm (forms.Form):

liste_auteurs = authorlist()

choix = forms.ChoiceField (choices = liste_auteurs, widget = forms.ChoiceField)

But again, although everything appears correct and functional, your system fails to interpret the commands.

Finally, the following syntax provides the main views:

from django.shortcuts import render

from django.http import HttpResponseRedirect, HttpResponse, JsonResponse

from django.shortcuts import render, redirect

from django.urls import reverse, reverse_lazy

from django.views import generic, decorators

from django.contrib.auth.models import User, Group

[…]

def test1 (request):

if request.method == ‘POST’:

form = TestForm (request.POST)

if form.is_valid():

form.save()

return HttpResponseRedirect (reverse (‘citatio/quote_list.html’))

else:

form = testform()

return render (request, ‘citatio/liste_auteurs.html’, {‘form’: form })

The documentation includes a specific file at the project’s root to introduce all API calls. However, this is irrelevant when reproducing the error log.

How To Fix the Max Retries Exceeded With URL Code Exception?

You can fix the maximum number of retries URL code exceptions by fixing the connections used by the Retry utility. On top of that, you can repair the project by introducing the requested feature that removes the flaws and introduces correct sessions for the primary functions.

Both solutions prevent other code complications and mistakes, which is vital when fixing your complex project or application. So, we will teach you how to improve the connection by providing a snippet for sending requests.

The example below provides this script:

import requests

from requests.adapters import HTTPAdapter, Retry

import time

def send_request(url,

n_retries = 5,

backoff_factor = 0.7,

status_codes = [505, 504, 490, 520, 422]):

sess = requests.Session()

retries = Retry (connect = n_retries, backoff_factor = backoff_factor,

status_forcelist = status_codes)

sess.mount (“https://”, HTTPAdapter (max_retries = retries))

sess.mount (“http://”, HTTPAdapter (max_retries = retries))

response = sess.get (url)

return response

Lastly, you can complete the debugging approach by timing the execution and calling the adequate functions. We explained this procedure in the following example:

# start the timer

start_time = time.time()

# send a request to GitHub API

url = “https://api.github.com/users”

response = send_request(url)

# print the status code

print(response.status_code)

# end timer

end_time = time.time()

# compute the run time

Print (“Run time: “, end_time-start_time)

As you can tell, we wrote several comments to help you understand the element’s purpose. Still, although you can copy and paste these commands to your document, changing the values and properties is critical to fit your application’s needs. First, however, use the following procedure if the error persists.

– Introduce the Request Feature Calculating the Public IP Addresses

An alternative solution suggests writing the requested feature to calculate the public IP addresses on any domain. This method prevents your system from experiencing request overflows when accessing any domain.Introduce the Request Feature Calculating the Public IP Addresses

In addition, this approach creates a mapping for the host files, debugging all functions.

You can learn about the correct syntax in the following example:

import socket

import subprocess

from typing import Tuple

ENDPOINT = ‘https://anydomainname.example.com/’

def get_public_ip() -> Tuple[str, str, str]:

my_public_ip : str

end_point_ip_address : str

Ip address of endpoint domain host.

end_point_domain : str

# bash_command = “””host myip.opendns.com resolver1.opendns.com |

# grep “myip.opendns.com has” | awk ‘{print $4}’”””

# bash_command = “””curl ifconfig.co”””

# bash_command = “””curl ifconfig.me”””

bash_command = “”” curl icanhazip.com”””

my_public_ip = subprocess.getoutput (bash_command)

my_public_ip = re.compile (“[0-9.]{4,}”).findall (my_public_ip) [0]

end_point_domain = (

ENDPOINT.replace (“https://”, “”)

.replace (“http://”, “”)

.replace (“/”, “”)

)

end_point_ip_address = socket.gethostbyname (end_point_domain)

return my_public_ip, end_point_ip_address, end_point_domain

def set_etc_host(ip_address: str, domain: str) -> str:

A function to write mapping of ip_address and domain name in /etc/hosts.

ip_address : str

domain : str

bash_command = “””echo “{} {}” >> /etc/hosts”””.format (ip_address, domain)

output = subprocess.getoutput (bash_command)

if __name__ == “__main__”:

my_public_ip, end_point_ip_address, end_point_domain = get_public_ip()

output = set_etc_host (ip_address = end_point_ip_address, domain = end_point_domain)

print (“My public IP address:”, my_public_ip)

print (“ENDPOINT public IP address:”, end_point_ip_address)

print (“ENDPOINT Domain Name:”, end_point_domain )

print (“Command output:”, output)

This example completes the second debugging procedure and fixes your program without interfering with other commands and properties.

Conclusion

The max retries exceeded URL code exception compromises your programming experience when the system fails to verify the SSL certificate. However, we fixed the inconsistency, so let’s have a look at the critical points discussed in this article:

  • We confirmed the exact error log when sending browser requests with unstable internet connections
  • Creating a form with a dropdown on API confuses your program and displays a warning
  • Fixing the connections used by the Retry utility is the most sophisticated debugging method that works for all documents

Your application should no longer experience this URL code exception because the connections and inputs are fully functional. In addition, you will avoid causing other complications and mistakes, although we suggest isolating the broken script.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Окунись в чувственную атмосферу

Открой

Твоя скидка 10% по промокоду: VIVAZZI

При работе с API в Контакте можно встретить следующий ответ:

{'error': 'Too many requests per second', 'error_code': 6}

Значение 6 ключа error_code говорит о том, что превышено допустимое количество обращений api в течение некоторого времени (обычно в течение секунды).

Обработать его можно достаточно легко, например:

import requests
import time


def get_vk_data(method, params, max_attempts=20):
    url = f'https://api.vk.com/method/{method}'
    attempt = 0
    while attempt < max_attempts:
        resp = requests.get(url, params=params)
        data = resp.json()

        if 'error' in data and data['error'].get('error_code') == 6:
            time.sleep(2)
            attempt += 1
            continue
        
        break

    return data

Другими словами, мы пытаемся получить ответ (в переменную data) до тех пор, пока либо не будет ошибки (покаdata не будет содержать ключ error), либо код ошибки будет отличный от 6. Также предусмотрим максимальное количество попыток получить данные.

В качестве примера приведу обновление (синхронизацию) информации пользователя ВК:

class VKUser(models.Model):
    vk_user_id = models.IntegerField(_('VK User ID'), null=True, blank=True)

    screen_name = models.CharField(_('Screen name'), max_length=100, blank=True)
    pic_url = models.URLField(_('Pic url'), blank=True)

    first_name = models.CharField(_('First name'), max_length=100)
    last_name = models.CharField(_('Last name'), max_length=100)

    def sync_data(self):
        params = {
            'v': '3.0',
            'access_token': settings.ACCESS_TOKEN,
            'user_ids': self.vk_user_id,
            'fields': 'first_name, last_name, screen_name, photo_100',
        }

        data = get_vk_data('users.get', params)['response'][0]

        self.first_name = data['first_name']
        self.last_name = data['last_name']
        self.screen_name = data.get('screen_name', '')
        self.pic_url = data['photo_100']

        self.save()

Метод sync_data() обновляет поля: имя и фамилия пользователя, а также его аватар и короткое имя (screen_name).

Теперь этот код можно использовать так:

for vk_user in VKUser.objects.all():
    vk_user.sync_data()

для того, чтобы обновить информацию о всех пользователях.

Обратите внимание, что можно было бы передать в params['user_ids] список id пользователей, чтобы в одном запросе получить информацию о всех нужных пользователях, а не в цикле поочерёдно получать информацию о пользователе. Но иногда нужно именно поочерёдно использовать для получения некоторых полей, например, counters (https://dev.vk.com/reference/objects/user#counters)

Оцените статью

После нажатия кнопки «Отправить» ваше сообщение будет доставлено мне на почту.

Артём Мальцев

Веб-разработчик, владеющий знаниями языка программирования Python, фреймворка Django, системы управления содержимым сайта Django CMS, платформы для создания интернет-магазина Django Shop и многих различных приложений, использующих эти технологии.

Права на использование материала, расположенного на этой странице https://vivazzi.pro/ru/it/vk-error-6/:

Разрешается копировать материал с указанием её автора и ссылки на оригинал без использования параметра rel="nofollow" в теге <a>. Использование:

Автор статьи: Артём Мальцев
Ссылка на статью: <a href="https://vivazzi.pro/ru/it/vk-error-6/">https://vivazzi.pro/ru/it/vk-error-6/</a>

Больше: Правила использования сайта

Представляю вашему вниманию книгу, написанную моим близким другом Максимом Макуриным: Секреты эффективного управления ассортиментом.

Книга предназначается для широкого круга читателей и, по мнению автора, будет полезна специалистам отдела закупок и логистики, категорийным и финансовым менеджерам, менеджерам по продажам, аналитикам, руководителям и директорам, в компетенции которых принятие решений по управлению ассортиментом.

Понравилась статья? Поделить с друзьями:
  • Как найти раздел для восстановления
  • Пароль должен отвечать требованиям сложности не активно как исправить
  • Как в ватсапе найти открытки для поздравления
  • Как можно найти айфон по imei
  • Как найти партнеров в сетевой маркетинг