Instabot python 429 error

Request returns 429 error! #1129 Comments Please follow the guide below Issues submitted without this template format will be ignored. You will be asked some questions and requested to provide some information, please read them carefully and answer completely. Put an x into all the boxes [ ] relevant to your issue (like so […]

Содержание

  1. Request returns 429 error! #1129
  2. Comments
  3. Please follow the guide below
  4. Before submitting an issue, make sure you have:
  5. Purpose of your issue?
  6. The following sections requests more details for particular types of issues, you can remove any section (the contents between the triple —) not applicable to your issue.
  7. For a bug report, you must include the Python version used, code that will reproduce the error, and the error log/traceback.
  8. Describe your issue
  9. alexwlchan/handling-http-429-with-tenacity
  10. Sign In Required
  11. Launching GitHub Desktop
  12. Launching GitHub Desktop
  13. Launching Xcode
  14. Launching Visual Studio Code
  15. Latest commit
  16. Git stats
  17. Files
  18. README.rst
  19. About
  20. Ошибка HTTP 429 Too Many Requests и методы ее исправления
  21. Причины появления ошибки сервера 429
  22. DDoS-атаки
  23. Некорректная работа плагинов WordPress
  24. Действия со стороны обычного пользователя

Request returns 429 error! #1129

Please follow the guide below

  • Issues submitted without this template format will be ignored.
  • You will be asked some questions and requested to provide some information, please read them carefully and answer completely.
  • Put an x into all the boxes [ ] relevant to your issue (like so [x]).
  • Use the Preview tab to see how your issue will actually look like.

Before submitting an issue, make sure you have:

  • Updated to the latest version
  • Read the README and docs
  • Searched the bugtracker for similar issues including closed ones

Purpose of your issue?

  • Bug report (encountered problems/errors)
  • Feature request (request for a new functionality)
  • Question
  • Other

The following sections requests more details for particular types of issues, you can remove any section (the contents between the triple —) not applicable to your issue.

For a bug report, you must include the Python version used, code that will reproduce the error, and the error log/traceback.

Paste the output of python -V here:

Describe your issue

2019-11-19 14:39:17,167 — ERROR — Request returns 429 error!
2019-11-19 14:39:17,167 — WARNING — That means ‘too many requests’. I’ll go to sleep for 5 minutes.

IG updated their api request limit or flow a few days ago, which means that after scraping users a few times and I will get blocked.

The amount does not matter, the block happens if it’s 500 or 2000+ users.

The block is also longer than 5 min. I feel it is for hours.

The text was updated successfully, but these errors were encountered:

Источник

alexwlchan/handling-http-429-with-tenacity

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

Handling HTTP 429 errors in Python

This repo contains an example of how to handle HTTP 429 errors with Python. If you get an HTTP 429, wait a while before trying the request again.

What is HTTP 429?

The HTTP 429 status code means «Too Many Requests», and it’s sent when a server wants you to slow down the rate of requests.

The 429 status code indicates that the user has sent too many requests in a given amount of time («rate limiting»).

The response representations SHOULD include details explaining the condition, and MAY include a Retry-After header indicating how long to wait before making a new request.

HTTP/1.1 429 Too Many Requests Content-Type: text/html Retry-After: 3600

One way to handle an HTTP 429 is to retry the request after a short delay, using the Retry-After header for guidance (if present).

How do you handle it in Python?

The tenacity library has some functions for handling retry logic in Python. This repo has an example of how to use tenacity to retry requests that returned an HTTP 429 status code.

The example uses urllib.request from the standard library, but this approach can be adapted for other HTTP libraries.

There are two functions in handle_http_429_errors.py :

  • retry_if_http_429_error() can be used as the retry keyword of @tenacity.retry . It retries a function if the function makes an HTTP request that returns a 429 status code.
  • wait_for_retry_after_header(underlying) can be used as the wait keyword of @tenacity.retry . It looks for the Retry-After header in the HTTP response, and waits for that long if present. If not, it uses the supplied fallback strategy.

In the example below, the get_url() function tries to request a URL. If it gets an HTTP 429 response, it waits up to three times before erroring out — either respecting the Retry-After header from the server, or 1 second between consecutive requests if not.

I wrote this as a proof-of-concept in a single evening. It’s not rigorously tested, but hopefully gives an idea of how you might do this if you wanted to implement it properly.

About

An example of how to use tenacity to retry HTTP 429 errors in Python

Источник

Ошибка HTTP 429 Too Many Requests и методы ее исправления

При взаимодействии с веб-ресурсами можно столкнуться с различными проблемами. Одна их таких проблем – ошибка с кодом 429 Too Many Requests. Существует две самые распространенные причины возникновения этой ошибки сервера, с которыми нам предстоит разобраться самостоятельно.

Причины появления ошибки сервера 429

DDoS-атаки

Начать следует с того, что чаще всего ошибка 429 сопровождается надписью «The user has sent too many requests in a given amount of time», что означает превышение ограничений по запросам к сайту. Соответственно, именно так происходит предотвращение DDoS-атак, которые и являются основной причиной появления рассматриваемой проблемы. Помимо самого кода, вы увидите и несколько других параметров:

Общее количество запросов.

Запросы с конкретного IP-адреса в секунду.

Количество одновременных запросов.

Общее количество запросов с одного IP-адреса.

Если же сама ошибка появляется при использовании поисковых систем или сторонних онлайн-сервисов, которые запрашивают доступ к сайту, вполне возможно, что их блокировка осуществляется со стороны хостинга в связи с тем, что количество запросов превышает ограничение. Для ее решения вам потребуется обратиться напрямую в техническую поддержку с просьбой разрешить подобные запросы.

В случае, когда есть уверенность в том, что ошибка http 429 появилась именно из-за атак на ваш ресурс, советую ознакомиться с отдельным материалом, в котором вы узнаете, как обезопасить себя от DDoS эффективными инструментами и банальными мерами предосторожности.

Некорректная работа плагинов WordPress

Вторая распространенная причина, которая может быть связана с регулярным появлением неполадки 429, – некорректное функционирование плагинов под управлением CMS WordPress. Для решения этой проблемы потребуется выполнить несколько несложных действий.

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

Что касается использования плагинов, то тут всегда лучше подключать только проверенные и качественные решения. Со списком таких плагинов предлагаю ознакомиться в материале по следующей ссылке.

Если после проверки неполадка все еще не исчезла, переключитесь на стандартную тему WordPress, которая называется Twenty Seventeen. Это действие поможет понять, связана ли ошибка сервера 429 со скриптами, которые входят в пользовательский шаблон оформления сайта. В том случае, когда трудность действительно была связана с темой, придется переделать ее вручную или же подыскать новый вариант для своего веб-ресурса.

Действия со стороны обычного пользователя

Обычный пользователь, который сталкивается с неполадкой 429 при попытке просмотреть конкретный сайт, не сможет ничего предпринять самостоятельно, чтобы решить ее. Однако, если есть возможность, стоит обратиться напрямую к владельцу интернет-ресурса или администраторам, сообщив им о появившейся ошибке. Так вы дадите понять, что сайт работает не так, как это нужно, и ускорите процесс решения трудностей.

Ошибка HTTP с кодом 429 – неприятная ситуация, которая может коснуться каждого владельца сайта. Из приведенного выше материала вы поняли, что существует две основные причины, которые могут ее вызывать. Теперь остается только разобраться с каждой из них и провести проверочные работы, чтобы оперативно исправить сложившуюся ситуацию.

Источник

Error occurring only when script is scheduled

I am using instabot to log into an instagram account.
I am getting a 429 error while running my script only when it is scheduled. The script runs with no issues in console.

This is the error:

2021-07-21 19:45:54,990 - INFO - Not yet logged in starting: PRE-LOGIN FLOW!
2021-07-21 19:45:55,038 - ERROR - Request returns 429 error!
2021-07-21 19:45:55,038 - WARNING - That means 'too many requests'. I'll go to sleep for 5 minutes.

Like I said, this only happens when the task is scheduled, and will not happen when I run it in console.

Beloved premium user

daaniel
|
5
posts
|



July 21, 2021, 11:52 p.m.

|
permalink

Scheduled tasks are running from a different server. Looks like the IP of the server running tasks could is rate limited by instagram as multiple users use it to connect to Instagram. Make your code sleep and try again.

Staff

fjl
|
3651
posts
|

PythonAnywhere staff
|



July 22, 2021, 9:10 a.m.

|
permalink

Thanks for the reply! Fortunately I was able to figure it out from another similar forum post. In case anyone else has this issue, cd’ing into the correct directory when scheduling the task is what fixed it for me(specifically for this one function that used Instabot, as the rest of my program up to that point ran normally, which is why I was so confused).

eg: cd /home/user/scriptlocation/; python3.9 /home/user/scriptlocation/script.py

Beloved premium user

daaniel
|
5
posts
|



July 22, 2021, 8:48 p.m.

|
permalink

Glad to hear that you made it work!

Staff

fjl
|
3651
posts
|

PythonAnywhere staff
|



July 23, 2021, 8:19 a.m.

|
permalink

Can you please elaborate about the cd’ing part, I am facing the same problem while using instabot

bananabond77
|
1
post
|



July 24, 2022, 8:32 a.m.

|
permalink

You need to cd into the directory that your code is expecting to be the working directory.

Staff

glenn
|
8703
posts
|

PythonAnywhere staff
|



July 24, 2022, 9:35 a.m.

|
permalink

Я пытаюсь запустить скрипт, который входит в Instagram и загружает 10 изображений со случайным текстом, который был сгенерирован. Однако вот вывод, который я получаю, когда пытаюсь запустить скрипт:

2023-01-02 21:56:48,608 - INFO - Instabot version: 0.117.0 Started
Which account do you want to use? (Type number)
1: ACCOUNTNAME
0: add another account.
-1: delete all accounts.
1
2023-01-02 21:56:51,371 - INFO - Not yet logged in starting: PRE-LOGIN FLOW!
2023-01-02 21:56:51,573 - ERROR - Request returns 429 error!
2023-01-02 21:56:51,573 - WARNING - That means 'too many requests'. I'll go to sleep for 5
minutes.

Как я могу исправить эту проблему?

Вот код, который я использую:

import random
import requests
from PIL import Image, ImageDraw, ImageFont
import time
import instabot

# Generate 10 random images
for i in range(10):
  # Create a black image
  image = Image.new('RGB', (500, 500), (0, 0, 0))
  draw = ImageDraw.Draw(image)

  # Generate a random string of white text
  text = ''.join([
    random.choice(
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{};:'",.<>/?')
    for i in range(10)
  ])
  # Use a default font with a larger size
  font = ImageFont.truetype('cour.ttf', 72)

  # Randomly position each letter on the image
  x = 0
  y = 0
  for letter in text:
    draw.text((x, y), letter, (255, 255, 255), font=font)
    x += random.randint(30, 50)
    y += random.randint(-10, 10)

  # Save the image and create a corresponding text file
  image.save(f'generated-images/image{i}.jpg')
  with open(f'generated-images/image{i}.txt', 'w') as f:
    f.write(text)

try:
  # Create an Instabot instance
  bot = instabot.Bot()

  # Login to Instagram
  bot.login()

  # For each image and corresponding text file
  for i in range(10):
    # Open the text file
    with open(f'generated-images/image{i}.txt', 'r') as f:
      # Use the text from the file as the caption
      caption = f.read()

  # Post the image and use the text from the file as the caption
  bot.upload_photo(f'generated-images/image{i}.jpg', caption=caption)

  # Add a delay between requests
  time.sleep(200)
except:
  print('Error')
finally:
  bot.logout()
  print('logging out')

# Log out of Instagram
bot.logout()

Он успешно вошел в мою учетную запись без ошибок, но когда он пытается опубликовать изображения, он выдает «ошибка 429» …

1 ответ

Не делай этого, когда ты устал. Попробуйте это вместо того, чтобы вздремнуть и посмотреть, сможете ли вы понять это, когда проснетесь


-2

Hacker man
3 Янв 2023 в 01:13

Понравилась статья? Поделить с друзьями:
  • Inst 08103 04 ошибка ман
  • Insql retrieval fatal error
  • Insomnia ssl connect error
  • Insomnia fatal error
  • Insmod normal error no such partition