簡體   English   中英

使用 ratelimit 庫在 Python 上設置 API 速率限制

[英]Setting API rate limit on Python with ratelimit library

 from ratelimit import limits, RateLimitException, sleep_and_retry
 from backoff import on_exception, expo
 max_hit = 5
 period = 300
 @limits(calls=max_hit, period=period)
    def StashNotes(self):
         url = ("https://www.r10.net/")
         raw_data = requests.get(url, headers=headers)
         if raw_data.status_code != 200:
              raise Exception('API response: {}'.format(raw_data.status_code))
         else:
                ## some unnecessary things here ##

我試圖將 API 速率限制為最大命中 5 和周期 300,因此我的 requests.get 在 300 秒內不會命中超過 5 次。 @limits(calls=max_hit,period=period) 不起作用,並且無法真正弄清楚原因。

除了 ratelimit 庫或如何修復 @limits 裝飾之外,還有其他方法可以做到這一點嗎? 任何一種解決方案都值得贊賞,謝謝。

headers=headers包含敏感信息,但無論如何它只包含 2 個 cookie 值並不重要。

當我嘗試在 API 上進行超過 5 次調用迭代時,它對我來說是異常的,在 5 次調用后出現異常,

ratelimit.exception.RateLimitException:調用太多

完整代碼:

from flask import Flask
from ratelimit import limits

max_hit = 5
period = 300

@limits(calls=max_hit, period=period)
def StashNotes():
    return "sany"

app = Flask(__name__)

@app.route("/")
def hello_world():
    return StashNotes()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM