2016-10-18 3 views
0

У меня есть следующее сообщение об ошибке:imgurpython.helpers.error.ImgurClientRateLimitError: Оценить предел превышен

/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. 
    InsecurePlatformWarning 
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. 
    InsecurePlatformWarning 
Traceback (most recent call last): 
    File "download.py", line 22, in <module> 
    search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) 
    File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 531, in gallery_search 
    response = self.make_request('GET', 'gallery/search/%s/%s/%s' % (sort, window, page), data) 
    File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 153, in make_request 
    raise ImgurClientRateLimitError() 
imgurpython.helpers.error.ImgurClientRateLimitError: Rate-limit exceeded! 

для этого кода:

1 from imgurpython import ImgurClient 
    2 import inspect 
    3 import random 
    4 import urllib2 
    5 import requests 
    6 from imgurpython.helpers.error import ImgurClientError 
    7 
    8 client_id = "ABC" 
    9 client_secret = "ABC" 
10 access_token = "ABC" 
11 refresh_token = "ABC" 
12 
13 
14 
15 image_type = ['jpg', 'jpeg'] 
16 
17 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 
18 
19 item_count = 0 
20 for p in range(1, 10000): 
21  try: 
22   search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) 
23   for i in range(0,https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f len(search)): 
24    item_count +=1 
25    print(search[i].comment_count) 
26    if search[i].comment_count > 10 and not search[i].is_album: 
27     print(search[i].type) 
28     if search[i].type[6:] in image_type: 
29      count = 0 
30      try: 
31       image_file = urllib2.urlopen(search[i].link, timeout = 5) 
32       image_file_name = 'images/'+ search[i].id+'.'+search[i].type[6:] 
33       output_image = open(image_file_name, 'wb') 
34       output_image.write(image_file.read()) 
35       for post in imgur_client.gallery_item_comments(search[i].id, sort='best'): 
36        if count <= 10: 
37         count += 1 
38       output_image.close() 
39      except urllib2.URLError as e: 
40       print(e) 
41       continue 
42      except socket.timeout as e: 
43       print(e) 
44       continue 
45      except socket.error as e: 
46       print(e) 
47       continue 
48  except ImgurClientError as e: 
49   print(e) 
50   continue 
51 
52 print item_count 

Также я вижу эту линию почти очень часто:

/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. 
    InsecurePlatformWarning 

Как исправить ошибку? Есть ли способ обхода ограничения скорости в Imgur? Поэтому я создаю это приложение для использования в научных исследованиях не для коммерческих целей, и, согласно https://api.imgur.com/#limits, он должен быть бесплатным, но мне нужно было зарегистрировать свое приложение, чтобы получить информацию, связанную с client_id. Как я могу установить приложение как некоммерческое, чтобы я не получил эту ошибку ограничения скорости или если все виды приложений получают эту ошибку, как мне ее обрабатывать? Как мне настроить свой код так, чтобы он выполнял только 1250 запросов в час?

Также здесь моя кредитная информация:

User Limit: 500 
User Remaining: 500 
User Reset: 2016-10-18 14:32:41 
User Client Limit: 12500 
User Client Remaining: 9570 

UPDATE: С сна (8), как предложено в ответ я в конечном итоге с этим происходит непрерывно. Для разных поисковых запросов это происходит на разных страницах. Как я могу исправить код, чтобы он прекратил выполнение, когда это произойдет? Вот соответствующий код обновления: https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f

page number is: 157 
0 
image/jpeg 
page number is: 157 
0 
page number is: 157 
0 
page number is: 157 
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. 
    InsecurePlatformWarning 
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. 
    InsecurePlatformWarning 
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. 
    InsecurePlatformWarning 
+0

Пожалуйста, задайте новый вопрос об этом предупреждении. – Soviut

ответ

1

Предел скорости относится к тому, как часто вы ударять API, а не сколько звонков вы разрешили. Для предотвращения взлома большинство API имеют ограничение скорости (например, 30 запросов в минуту, 1 раз в 2 секунды). Ваш скрипт делает запросы как можно быстрее, в сотни или даже тысячи раз быстрее, чем предел.

Чтобы предотвратить сканирование вашего скрипта, самым простым решением является введение sleep в цикл for.

from time import sleep 

for i in range(10000): 
    print i 
    sleep(2) # seconds 

Отрегулируйте время сна как минимум на одну секунду больше, чем определяет API как его предел скорости.

https://api.imgur.com/#limits

The Imgur API uses a credit allocation system to ensure fair distribution of capacity. Each application can allow approximately 1,250 uploads per day or approximately 12,500 requests per day. If the daily limit is hit five times in a month, then the app will be blocked for the rest of the month. The remaining credit limit will be shown with each requests response in the X-RateLimit-ClientRemaining HTTP header.

Так запросы 12500/24 ​​часа 520 запросов в час или ~ 8 в минуту. Это означает, что ваш сон должен составлять около 8 секунд.

+0

Я знаю, что могу делать только 1250 запросов в час, но сколько сна вы бы оценили для этого? –

+0

Я принимаю ответ, поскольку он работает для меня со сном (2). Я буду комментировать позже, если снова увижу ту же ошибку! Спасибо :) –

+0

если у вас есть шанс, пожалуйста, посмотрите http://stackoverflow.com/questions/40116518/only-limited-number-of-pages-can-be-retrieved –

Смежные вопросы