【问题标题】:Python: Need to request only 20 times per minutePython:每分钟只需要请求 20 次
【发布时间】:2016-01-17 01:25:30
【问题描述】:

我制作了一个使用 api 请求一些数据的 python 代码,但是 api 只允许每分钟 20 个请求。我正在使用 urllib 来请求数据。我也使用 for 循环,因为数据位于文件中:

for i in hashfile:
    hash = i
    url1 = "https://hashes.org/api.php?act=REQUEST&key="+key+"&hash="+hash
    print(url1)
    response = urllib.request.urlopen(url2).read()
    strr = str(response)

    if "plain" in strr:
        parsed_json = json.loads(response.decode("UTF-8"))
        print(parsed_json['739c5b1cd5681e668f689aa66bcc254c']['plain'])
        writehash = i+parsed_json
        hashfile.write(writehash + "\n")
    elif "INVALID HASH" in strr:
        print("You have entered an invalid hash.")
    elif "NOT FOUND" in strr:
        print("The hash is not found.")
    elif "LIMIT REACHED" in strr:
        print("You have reached the max requests per minute, please try again in one minute.")
    elif "INVALID KEY!" in strr:
        print("You have entered a wrong key!")
    else:
        print("You have entered a wrong input!")

有没有办法让它每分钟只执行 20 个请求?或者如果这不可能,我可以在 20 次尝试后让它超时吗? (顺便说一句,这只是代码的一部分)

【问题讨论】:

    标签: python timer request timeout urllib


    【解决方案1】:

    time.sleep(3) 保证您的代码每分钟不会发出超过 20 个请求,但它可能会不必要地延迟允许的请求:假设您只需要发出 10 个请求:time.sleep(3) 在每个请求使循环运行之后半分钟,但在这种情况下,api 允许您一次发出所有 10 个请求(或至少一个紧接着一个)。

    要在不延迟初始请求的情况下强制执行每分钟 20 个请求的限制,您可以使用 RatedSemaphore(20, period=60)

    rate_limit = RatedSemaphore(20, 60)
    for hash_value in hash_file:
        with rate_limit, urlopen(make_url(hash_value)) as response:
            data = json.load(response)
    

    您甚至可以在遵守速率限制的情况下一次发出多个请求:

    from multiprocessing.pool import ThreadPool
    
    def make_request(hash_value, rate_limit=RatedSemaphore(20, 60)):
        with rate_limit:
            try:
                with urlopen(make_url(hash_value)) as response:
                    return json.load(response), None
            except Exception as e:
                    return None, e
    
    
    pool = ThreadPool(4) # make 4 concurrent requests
    for data, error in pool.imap_unordered(make_request, hash_file):
        if error is None:
            print(data)
    

    【讨论】:

      【解决方案2】:

      您想使用time 模块。在每个循环的末尾添加一个time.sleep(3),您将每分钟最多收到 20 个请求。

      【讨论】:

      • 也记得import time
      猜你喜欢
      • 2016-01-27
      • 1970-01-01
      • 2013-11-29
      • 2018-10-11
      • 1970-01-01
      • 2018-12-24
      • 2011-06-23
      • 2020-02-28
      • 1970-01-01
      相关资源
      最近更新 更多