דוגמה לתזמון Shift

הדוגמה הבאה ממחישה איך לקרוא ל-API עם ספריית requests של Python, באמצעות מפתח API לאימות. כדי להשתמש בה:

  • מתקינים את ספריית requests של Python. משורת הפקודה: 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, המועד האחרון של השרת הוא השימושי ביותר, כי הוא מציין לשרת הקצה העורפי כמה זמן צריך לקבל בקשה, להפעיל את הפותר הבסיסי ולהחזיר תגובה. לעומת זאת, מועדי יעד הם שימושיים כדי להגדיר את משך הזמן המקסימלי שבו אפליקציית הלקוח (כלומר האפליקציה שקוראת ל-API OR) תמתין לתגובה, לפני שהתזמון יסתיים.

קטע הקוד הבא מגדיר גם תאריך יעד של לקוח וגם תאריך יעד של שרת בכותרות הסשן של הבקשה. זמן היעד שנקבע ללקוח הוא 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)