如何修复亚马逊EC2上Python脚本调用Binance时的无效JSON错误?
问题
在亚马逊EC2实例上运行Python脚本,初期运行正常,但一段时间后出现以下错误:
Invalid JSON error message from Binance: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <TITLE>ERROR: The request could not be satisfied</TITLE> </HEAD><BODY> <H1>503 ERROR</H1> <H2>The request could not be satisfied.</H2> <HR noshade size="1px"> This distribution exceeded the limit on requests per second. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. <BR clear="all"> If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation. <BR clear="all"> <HR noshade size="1px"> <PRE> Generated by cloudfront (CloudFront) Request ID: uQnEmv-kXx0j2v3WdxnbrkBlJDdI33fduqBNYhNoIVfv10G1_LZS1Q== </PRE> <ADDRESS> </ADDRESS> </BODY></HTML>
脚本设置为每隔1分钟请求一次数据,目前找不到该错误的相关解决信息。
解决方案
- 核对Binance API限流规则:即便设置1分钟1次请求,Binance的API限流可能按IP维度统计累计请求量,比如你使用的EC2公共网段内其他用户的请求,可能导致该IP段总请求量超标。确认是否触发了IP级别的限流阈值。
- 添加指数退避重试逻辑:针对503错误,在代码中实现重试机制,每次失败后等待时长翻倍,避免持续触发限流。示例代码:
import time import requests def get_binance_data(api_url, max_retries=3): for retry_count in range(max_retries): try: resp = requests.get(api_url) resp.raise_for_status() return resp.json() except requests.exceptions.HTTPError: if resp.status_code == 503 and retry_count < max_retries - 1: time.sleep(2 ** retry_count) continue raise - 更换EC2弹性IP或使用代理:若当前EC2所在IP被限流,给实例分配新的弹性IP,或通过代理IP分散请求来源,降低单一IP的请求压力。
- 排查脚本隐性重复请求:检查脚本是否存在多进程/多线程重复执行、定时任务重复触发的情况,确保实际请求频率确实是1分钟1次。
- 联系Binance官方支持:若以上方法无效,提交工单说明你的请求频率和限流问题,确认是否存在账号或IP误判限流的情况。
内容的提问来源于stack exchange,提问作者Brian Daniel
相关产品推荐
相关产品推荐

