在向 API 发起请求时,通常会遇到速率限制,这些限制限制了在特定时间范围内可以发出的调用次数。GitHub Copilot Chat 可以帮助你处理这些限制,通过建议代码来检测速率限制响应,并在延迟后自动重试请求。
示例情景
以下 Python 代码从外部 API 获取天气数据。如果该 API 存在速率限制,当超过限制时请求可能会失败,你的应用需要一种优雅处理这些响应的方式,即实现重试逻辑。
from flask import Flask, request
import requests
app = Flask(__name__)
WEATHER_API_URL = "https://api.example.com/weather"
@app.route('/get_weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
# Simulate an API request to the external weather service
response = requests.get(WEATHER_API_URL, params={"city": city})
weather_data = response.json()
return weather_data
示例提示
How can I handle API rate limits within get_weather().
from flask import Flask, request
import requests
app = Flask(__name__)
WEATHER_API_URL = "https://api.example.com/weather"
@app.route('/get_weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
# Simulate an API request to the external weather service
response = requests.get(WEATHER_API_URL, params={"city": city})
weather_data = response.json()
return weather_data
How can I handle API rate limits within get_weather().
How can I handle API rate limits within get_weather().
示例回复
注意
以下响应为示例。Copilot Chat 的回复具有不确定性,您可能会得到与此处显示的不同的响应。
Copilot 可能会建议实现带指数退避的重试机制,以限制重试尝试的频率。
例如
import requests
from flask import Flask, request
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
app = Flask(__name__)
WEATHER_API_URL = "https://api.example.com/weather"
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None,
):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
@app.route('/get_weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
try:
response = requests_retry_session().get(WEATHER_API_URL, params={"city": city})
response.raise_for_status()
weather_data = response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}, 500
return weather_data
在本示例中,Copilot 的建议包括设置一个重试会话,使代码在因特定状态码(500、502、504)导致请求失败时能够自动重试。backoff_factor 会逐渐增加重试之间的延迟,从而帮助避免进一步超出 API 的速率限制。