How to limit rate of requests to web services in Python?

后端 未结 6 1915
醉梦人生
醉梦人生 2020-12-30 06:13

I\'m working on a Python library that interfaces with a web service API. Like many web services I\'ve encountered, this one requests limiting the rate of requests. I would l

6条回答
  •  悲哀的现实
    2020-12-30 06:31

    Queuing may be overly complicated. A simpler solution is to give your class a variable for the time the service was last called. Whenever the service is called (!1), set waitTime to delay - Now + lastcalltime. delay should be equal to the minimum allowable time between requests. If this number is positive, sleep for that long before making the call (!2). The disadvantage/advantage of this approach is that it treats the web service requests as being synchronous. The advantage is that it is absurdly simple and easy to implement.

    • (!1): Should happen right after receiving a response from the service, inside the wrapper (probably at the bottom of the wrapper).
    • (!2): Should happen when the python wrapper around the web service is called, at the top of the wrapper.

    S.Lott's solution is more elegant, of course.

提交回复
热议问题