网络设计示例
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
以下示例展示了如何使用 Python requests
调用该 API
库,使用 API 密钥进行身份验证。要使用此应用,请执行以下操作:
- 安装 Python
requests
库。在命令行中:pip install
requests
。
- 将以下 Python 程序保存到计算机,并将其命名为
example.py
。
- 将 example_request.json 文件保存到
程序(这是一个示例 JSON 请求)。
- 在程序所在的目录中创建一个
credentials.json
文件,其中包含 {"key": "your_api_key"}
- 从命令行运行该示例:
python example.py
。
# example.py
import json
import requests
def run_example():
"""Calls the OR API to solve a shift scheduling problem."""
# Endpoint for the workforce scheduling solver in the OR API.
end_point = "https://optimization.googleapis.com/v1/shipping:designShippingNetwork"
# Read the API Key from a JSON file with the format:
# {"key": "your_api_key"}
with open("credentials.json") as f:
credentials = json.load(f)
api_key = credentials["key"]
# Load the JSON file with the request.
with open("example_request.json", "r") as f:
json_request = json.load(f)
# Call the API post method.
response = requests.post(f"{end_point}?key={api_key}", json=json_request)
# Process the response.
if response.ok:
solution = json.loads(response.content)
with open("example_response.json", "w") as f:
json.dump(solution, f, indent=2)
print(solution)
else:
error = json.loads(response.content)["error"]
print(f'Status code {error["code"]}: {error["message"]}')
if __name__ == "__main__":
run_example()
如何设置截止日期?
期限用于确定对 API 的调用应花费的最长时钟时间。用户可以设置客户端和服务器截止期限。在 OR API 中,
服务器截止时间更有用,因为它会告知后端服务器
来接收请求、运行底层求解器,并返回
响应。相比之下,客户截止期限则适用于设置
客户端应用(即调用 OR API 的应用)将进入
在超时之前等待响应。
以下代码段会在请求的会话标头中设置客户端和服务器截止期限。客户端截止期限设置为 60 秒。通过
服务器截止期限应短于考虑的客户期限
通信开销在这里,我们将服务器截止时间设置为客户端时间的 95%
但此期限可能会因申请而异请注意
键也移到了会话标头中,以进行 session.post(...)
调用
更简洁。
# Call the API post method.
session = requests.Session()
client_deadline_seconds = 60
server_deadline_seconds = 0.95 * client_deadline_seconds
session.headers = {
"Content-Type": "application/json",
"Connection": "keep-alive",
"Keep-Alive": f"timeout={client_deadline_seconds}, max=1",
"X-Server-Timeout": f"{server_deadline_seconds}",
"X-Goog-Api-Key": api_key,
}
response = session.post(end_point, json=json_request, timeout=client_deadline_seconds)
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-09-12。
[null,null,["最后更新时间 (UTC):2024-09-12。"],[[["\u003cp\u003eThis page provides a Python example using the \u003ccode\u003erequests\u003c/code\u003e library to call the Optimization API and solve a shipping network design problem.\u003c/p\u003e\n"],["\u003cp\u003eIt includes instructions for installing dependencies, setting up authentication with an API key, and running the example code.\u003c/p\u003e\n"],["\u003cp\u003eUsers can set deadlines for API calls, including client and server deadlines, to control the maximum execution time.\u003c/p\u003e\n"],["\u003cp\u003eThe example demonstrates how to load a JSON request, send it to the API endpoint, and process the response, including error handling.\u003c/p\u003e\n"]]],["The provided code demonstrates using the Python `requests` library to call an API. Key actions include installing `requests`, creating `example.py`, `example_request.json`, and `credentials.json` files. The `example.py` program reads API credentials and a JSON request, posts the request to the API endpoint, and then saves the API response in `example_response.json`. Deadlines can be set in the request headers, including both client and server, to limit the time allowed for the API call.\n"],null,["# Network Design Example\n\nThe following example showcases how to call the API with the Python `requests`\nlibrary, using an API key for authentication. To use it:\n\n- Install the Python `requests` library. From your command line: `pip install\n requests`.\n- Save the following Python program to your computer, naming it `example.py`.\n- Save the [example_request.json](/static/optimization/service/shipping/design_shipping_network_request.json) file in the same directory as your program (this is a sample JSON [request](/optimization/service/reference/rest/v1/shipping/designShippingNetwork)).\n- Create a `credentials.json` file in the same directory as your program, with `{\"key\": \"your_api_key\"}`\n- Run the example from the command line: `python example.py`.\n\n\n # example.py\n import json\n import requests\n\n def run_example():\n \"\"\"Calls the OR API to solve a shift scheduling problem.\"\"\"\n \n # Endpoint for the workforce scheduling solver in the OR API.\n end_point = \"https://optimization.googleapis.com/v1/shipping:designShippingNetwork\"\n \n # Read the API Key from a JSON file with the format:\n # {\"key\": \"your_api_key\"}\n with open(\"credentials.json\") as f:\n credentials = json.load(f)\n api_key = credentials[\"key\"]\n\n # Load the JSON file with the request.\n with open(\"example_request.json\", \"r\") as f:\n json_request = json.load(f)\n\n # Call the API post method.\n response = requests.post(f\"{end_point}?key={api_key}\", json=json_request)\n\n # Process the response.\n if response.ok:\n solution = json.loads(response.content)\n with open(\"example_response.json\", \"w\") as f:\n json.dump(solution, f, indent=2)\n print(solution)\n else:\n error = json.loads(response.content)[\"error\"]\n print(f'Status code {error[\"code\"]}: {error[\"message\"]}')\n\n if __name__ == \"__main__\":\n run_example()\n\nHow to set deadlines?\n---------------------\n\nA deadline determines the maximum wall time that a call to the API should take.\nA user can set both client and server deadlines. In the context of the OR API, a\nserver deadline is the more useful one as it informs the backend server of how\nmuch time it has to receive a request, run the underlying solver, and return a\nresponse. In contrast, client deadlines are useful to set the maximum time that\nthe client application (i.e., the application calling the OR API) is going to\nwait for a response, before timing out.\n\nThe following code snippet sets both a client and a server deadline in the\nsession headers of the request. The client deadline is set to 60 seconds. The\nserver deadline should be less than the client deadline to account for\ncommunication overhead. Here we set the server deadline to be 95% of the client\ndeadline, but this can vary depending on the application. Notice that the API\nkey was also moved to the session headers to make the `session.post(...)` call\ncleaner. \n\n\n\n # Call the API post method.\n session = requests.Session()\n client_deadline_seconds = 60\n server_deadline_seconds = 0.95 * client_deadline_seconds\n session.headers = {\n \"Content-Type\": \"application/json\",\n \"Connection\": \"keep-alive\",\n \"Keep-Alive\": f\"timeout={client_deadline_seconds}, max=1\",\n \"X-Server-Timeout\": f\"{server_deadline_seconds}\",\n \"X-Goog-Api-Key\": api_key,\n }\n response = session.post(end_point, json=json_request, timeout=client_deadline_seconds)"]]