python - 无法在 Matrix Routing v8 HereMaps API 上验证异步请求
问题描述
我有一个有效的 HereMaps API 密钥,并且我正在使用 python requests
lib 对一个链接执行 GET 请求,该链接是在进行异步调用后返回的。我正在尝试像这样执行它:
即使我之前提供了正确的密钥来生成上面的这个链接,上面这个请求的结果仍然返回:
{
"error": "Unauthorized",
"error_description": "No credentials found"
}
我们应该如何进行身份验证以检查 Matrix Routing v8 API 上异步请求的状态结果?
解决方案
您可以使用两种身份验证方法来使用 HERE API:API 密钥和 OAuth 令牌。
由于处理凭据的方式,当您发出异步请求时,您需要在使用 API 密钥时禁用自动客户端重定向,因为客户端不会apiKey
再次将参数添加到已重定向到的 URL。
使用 Python 和 时,这个问题有很多解决方案requests
,这里有一个完整的例子可能会有所帮助:
import requests, time
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# "Profile mode (car fastest)" example request
request = {
"origins": [{"lat": 52.5309, "lng": 13.3849}, {"lat": 54.0924, "lng": 12.0991}],
"destinations": [
{"lat": 51.3397, "lng": 12.3731},
{"lat": 51.0504, "lng": 13.7373},
],
"regionDefinition": {"type": "world"},
"profile": "carFast",
}
# Using a Session object allows you to persist certain parameters accross requests
# see: https://requests.readthedocs.io/en/master/user/advanced/
session = requests.Session()
# Add `?apiKey=xxxxxx` to all requests
session.params = {"apiKey": api_key}
# Raise an exception for any non 2xx or 3xx HTTP return codes
session.hooks = {"response": lambda r, *args, **kwargs: r.raise_for_status()}
# Send an asynchronous request, see: https://developer.here.com/documentation/matrix-routing-api/8.3.0/dev_guide/topics/get-started/asynchronous-request.html
status_response = session.post(
"https://matrix.router.hereapi.com/v8/matrix", json=request
).json()
# Polling for the job status for 100 times
# You might want to use exponential back-off instead of time.sleep
for _ in range(0, 100):
# do not follow the redirect here
status_response = session.get(
status_response["statusUrl"], allow_redirects=False
).json()
if status_response["status"] == "completed":
# download the result
matrix_response = session.get(status_response["resultUrl"]).json()
print(matrix_response)
break
elif status_response["accepted"] or status_response["inProgress"]:
continue
else:
print(f"An error occured: {status_response}")
break
time.sleep(0.5) # sleep for 500 ms
免责声明:我在 HERE Technologies 从事矩阵路由工作。
推荐阅读
- firebase - 为什么在 google play store 上发布后 google 和 facebook 登录不起作用
- hibernate - 无法使用休眠执行更新
- c - 在 C 中初始化变量的最有效方法
- c++ - 如何将字符串添加到向量(并随后显示它)?
- asp.net-core - ASP.NET Core:如何在 startup.cs 文件中运行 npm 脚本命令?
- audio - 如何拦截、处理然后将音频发送到应用程序?
- android - 响应{protocol=h2, code=200, message=, url=https://airportparkingspecials.com/dam1.php}
- python - 将 NETCDF 转换为 CSV 列表
- javascript - Login.js:6 Uncaught TypeError: Cannot read property 'then' of undefined
- javascript - Vue.js 中 DatePicker 的日期格式