我正在使用GRequests和lxml在Python 2.7.3中编写一个小脚本,这将允许我从各个网站收集一些可收集的卡片价格并进行比较。问题是其中一个网站限制了请求数量,如果我超过它,则发回HTTP错误429。
有没有办法在GRequestes中添加限制请求数量,这样我就不会超过我指定的每秒请求数? 另外 - 如果发生HTTP 429,如何在一段时间后重新进行GRequestes重试?
另一方面 - 他们的限制非常低。每15秒就有8个请求。我多次使用浏览器将其破坏,只需刷新页面等待价格变动。
答案 0 :(得分:25)
要回答我自己的问题,因为我必须自己解决这个问题,而且似乎很少有关于此问题的信息。
这个想法如下。与GRequests一起使用的每个请求对象都可以在创建时将会话对象作为参数。另一方面,会话对象可以安装在发出请求时使用的HTTP适配器。通过创建我们自己的适配器,我们可以拦截请求并以我们最适合我们应用程序的方式对它们进行速率限制。在我的情况下,我最终得到了以下代码。
用于限制的对象:
DEFAULT_BURST_WINDOW = datetime.timedelta(seconds=5)
DEFAULT_WAIT_WINDOW = datetime.timedelta(seconds=15)
class BurstThrottle(object):
max_hits = None
hits = None
burst_window = None
total_window = None
timestamp = None
def __init__(self, max_hits, burst_window, wait_window):
self.max_hits = max_hits
self.hits = 0
self.burst_window = burst_window
self.total_window = burst_window + wait_window
self.timestamp = datetime.datetime.min
def throttle(self):
now = datetime.datetime.utcnow()
if now < self.timestamp + self.total_window:
if (now < self.timestamp + self.burst_window) and (self.hits < self.max_hits):
self.hits += 1
return datetime.timedelta(0)
else:
return self.timestamp + self.total_window - now
else:
self.timestamp = now
self.hits = 1
return datetime.timedelta(0)
HTTP适配器:
class MyHttpAdapter(requests.adapters.HTTPAdapter):
throttle = None
def __init__(self, pool_connections=requests.adapters.DEFAULT_POOLSIZE,
pool_maxsize=requests.adapters.DEFAULT_POOLSIZE, max_retries=requests.adapters.DEFAULT_RETRIES,
pool_block=requests.adapters.DEFAULT_POOLBLOCK, burst_window=DEFAULT_BURST_WINDOW,
wait_window=DEFAULT_WAIT_WINDOW):
self.throttle = BurstThrottle(pool_maxsize, burst_window, wait_window)
super(MyHttpAdapter, self).__init__(pool_connections=pool_connections, pool_maxsize=pool_maxsize,
max_retries=max_retries, pool_block=pool_block)
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
request_successful = False
response = None
while not request_successful:
wait_time = self.throttle.throttle()
while wait_time > datetime.timedelta(0):
gevent.sleep(wait_time.total_seconds(), ref=True)
wait_time = self.throttle.throttle()
response = super(MyHttpAdapter, self).send(request, stream=stream, timeout=timeout,
verify=verify, cert=cert, proxies=proxies)
if response.status_code != 429:
request_successful = True
return response
设定:
requests_adapter = adapter.MyHttpAdapter(
pool_connections=__CONCURRENT_LIMIT__,
pool_maxsize=__CONCURRENT_LIMIT__,
max_retries=0,
pool_block=False,
burst_window=datetime.timedelta(seconds=5),
wait_window=datetime.timedelta(seconds=20))
requests_session = requests.session()
requests_session.mount('http://', requests_adapter)
requests_session.mount('https://', requests_adapter)
unsent_requests = (grequests.get(url,
hooks={'response': handle_response},
session=requests_session) for url in urls)
grequests.map(unsent_requests, size=__CONCURRENT_LIMIT__)
答案 1 :(得分:9)
看看这个自动请求限制: https://pypi.python.org/pypi/RequestsThrottler/0.2.2
您可以在每个请求之间设置固定数量的延迟,或者在固定的秒数内设置要发送的请求数量(这基本上是相同的):
import requests
from requests_throttler import BaseThrottler
request = requests.Request(method='GET', url='http://www.google.com')
reqs = [request for i in range(0, 5)] # An example list of requests
with BaseThrottler(name='base-throttler', delay=1.5) as bt:
throttled_requests = bt.multi_submit(reqs)
其中函数multi_submit
返回ThrottledRequest
列表(请参阅文档末尾的链接)。
然后,您可以访问回复:
for tr in throttled_requests:
print tr.response
或者,您可以通过指定在固定时间内发送的号码或请求(例如每60秒15次请求)来实现相同目的:
import requests
from requests_throttler import BaseThrottler
request = requests.Request(method='GET', url='http://www.google.com')
reqs = [request for i in range(0, 5)] # An example list of requests
with BaseThrottler(name='base-throttler', reqs_over_time=(15, 60)) as bt:
throttled_requests = bt.multi_submit(reqs)
无需使用with
语句即可实现这两种解决方案:
import requests
from requests_throttler import BaseThrottler
request = requests.Request(method='GET', url='http://www.google.com')
reqs = [request for i in range(0, 5)] # An example list of requests
bt = BaseThrottler(name='base-throttler', delay=1.5)
bt.start()
throttled_requests = bt.multi_submit(reqs)
bt.shutdown()
答案 2 :(得分:1)
看起来没有任何简单的机制来处理请求或grequests代码的内置。似乎唯一的钩子就是回应。
这是一个超级hacky解决方案,至少证明它是可能的 - 我修改了grequests以保留发出请求的时间列表并休眠AsyncRequest的创建,直到每秒请求数低于最大值。 / p>
class AsyncRequest(object):
def __init__(self, method, url, **kwargs):
print self,'init'
waiting=True
while waiting:
if len([x for x in q if x > time.time()-15]) < 8:
q.append(time.time())
waiting=False
else:
print self,'snoozing'
gevent.sleep(1)
您可以使用grequests.imap()以交互方式观看
import time
import rg
urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com',
'http://www.cnn.com',
]
def print_url(r, *args, **kwargs):
print(r.url),time.time()
hook_dict=dict(response=print_url)
rs = (rg.get(u, hooks=hook_dict) for u in urls)
for r in rg.imap(rs):
print r
我希望有一个更优雅的解决方案,但到目前为止我找不到一个。在会话和适配器中查看。也许泳池管理员可以改为增强?
此外,我不会将此代码投入生产 - 'q'列表永远不会被修剪,最终会变得非常大。另外,我不知道它是否真的像宣传的那样工作。它看起来就像是在我查看控制台输出时。
唉。只看这段代码,我可以告诉它凌晨3点。是时候去睡觉了。
答案 3 :(得分:1)
我有类似的问题。这是我的解决方案。在你的情况下,我会这样做:
def worker():
with rate_limit('slow.domain.com', 2):
response = requests.get('https://slow.domain.com/path')
text = response.text
# Use `text`
假设您有多个域名正在剔除,我会设置一个字典映射(domain, delay)
,这样您就不会达到速率限制。
此代码假设您将使用gevent和monkey patch。
from contextlib import contextmanager
from gevent.event import Event
from gevent.queue import Queue
from time import time
def rate_limit(resource, delay, _queues={}):
"""Delay use of `resource` until after `delay` seconds have passed.
Example usage:
def worker():
with rate_limit('foo.bar.com', 1):
response = requests.get('https://foo.bar.com/path')
text = response.text
# use `text`
This will serialize and delay requests from multiple workers for resource
'foo.bar.com' by 1 second.
"""
if resource not in _queues:
queue = Queue()
gevent.spawn(_watch, queue)
_queues[resource] = queue
return _resource_manager(_queues[resource], delay)
def _watch(queue):
"Watch `queue` and wake event listeners after delay."
last = 0
while True:
event, delay = queue.get()
now = time()
if (now - last) < delay:
gevent.sleep(delay - (now - last))
event.set() # Wake worker but keep control.
event.clear()
event.wait() # Yield control until woken.
last = time()
@contextmanager
def _resource_manager(queue, delay):
"`with` statement support for `rate_limit`."
event = Event()
queue.put((event, delay))
event.wait() # Wait for queue watcher to wake us.
yield
event.set() # Wake queue watcher.
答案 4 :(得分:1)
那些想要更好地掌握节流/速率限制的人可以使用以下 Python 库: 速率限制 2.2.1:https://pypi.org/project/ratelimit/
ratelimit 2.2.1:这个包引入了一个函数装饰器,防止函数被调用的频率超过 API 提供者允许的频率。这应该可以防止 API 提供商通过遵守其速率限制来禁止您的应用程序。
来自 ratelimit 导入限制
导入请求
55 分钟 = 900
@limits(calls=15, period=FIFTEEN_MINUTES) def call_api(url): response = requests.get(url)
if response.status_code != 200:
raise Exception('API response: {}'.format(response.status_code))
return response