シフトのスケジューリングの例

次の例は、認証に 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% に設定していますが、これはアプリケーションによって異なります。session.post(...) 呼び出しをよりわかりやすくするために、API キーもセッション ヘッダーに移動されています。



# 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)