調節排程範例

以下範例說明如何透過 Python requests 程式庫,使用 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/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)