轮班安排示例

以下示例展示了如何使用 API 密钥进行身份验证,通过 Python requests 库调用 API。要使用此应用,请执行以下操作:

  • 安装 Python requests 库。从命令行:pip install requests
  • 将以下 Python 程序保存到计算机,并将其命名为 example.py
  • example_request.json 文件保存到程序所在的同一目录中(这是一个示例 JSON 请求)。
  • 使用 {"key": "your_api_key"} 在程序所在的目录中创建一个 credentials.json 文件
  • 从命令行运行该示例: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/scheduling:solveShiftScheduling"
    
    # 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%,但这可能因应用而异。请注意,API 密钥也已移至会话标头,以使 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)