eightmoons

commented.py

Oct 16th, 2022
1,136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.01 KB | None | 0 0
  1. import urllib.parse
  2. import requests
  3.  
  4. main_api = "https://www.mapquestapi.com/directions/v2/route?"
  5. key = ""
  6.  
  7.  
  8. def show_error(status, message):
  9.     print('******************************************')
  10.     print(f'Status Code: {str(status)}; {message}')
  11.     print('******************************************\n')
  12.  
  13. # [value] = value ng cell
  14. # [longest_str] = longest string sa isang row
  15. # [last] = string na pwede idagdag sa huli ng cell
  16. # mag ge-generate ito ng row na may complete whitespaces para pantay
  17. def row_builder(value, longest_str, last=""):
  18.     return f'{value}{" " * ((longest_str) - len(value))}{last}'
  19.  
  20.  
  21. while True:
  22.     orig = input("Starting Location: ")
  23.     if orig in ["q", "orig"]:
  24.         break
  25.     dest = input("Destination: ")
  26.     if dest in ["q", "quit"]:
  27.         break
  28.     url = main_api + urllib.parse.urlencode({
  29.         "key": key,
  30.         "from": orig,
  31.         "to": dest,
  32.     })
  33.     print("URL: " + url)
  34.     json_data = requests.get(url).json()
  35.     json_status = json_data["info"]["statuscode"]
  36.     if json_status == 0:
  37.         kms = []
  38.         narratives = []
  39.         # [1] ilagay lahat ng direction (narratives) at distance sa isang list
  40.         for route in json_data["route"]["legs"][0]["maneuvers"]:
  41.             kms.append(f' {str("{:.2f}".format((route["distance"]) * 1.61))} km  ')
  42.             narratives.append(f' {route["narrative"]}  ')
  43.         # [2] kunin yung may pinakamahabang length at istore sa variable
  44.         longest_narrative_str = len(max(narratives, key=len))
  45.         longest_kms = len(max(kms, key=len))
  46.         # [3] info = 1st column
  47.         info = [
  48.             " Trip Duration ",
  49.             " Kilometers ",
  50.             " Fuel Used (Ltr) ",
  51.         ]
  52.         # [4] values = 2nd column
  53.         values = [
  54.             f' {json_data["route"]["formattedTime"]}  ',
  55.             f' {str("{:.2f}".format((json_data["route"]["distance"]) * 1.61))}  ',
  56.             f' {str("{:.2f}".format((json_data["route"]["fuelUsed"]) * 3.78))}  ',
  57.         ]
  58.         # same process ng sa [2]
  59.         longest_info = len(max(info, key=len))
  60.         longest_values = len(max(values, key=len))
  61.         print(f'API Status: {str(json_status)} = A successful route call')
  62.         # [5] table1 1st table na magegenerate, nilagay ko sa variable [table1_corner] kase tatlong beses ko sya tatawagin. ang p-print nito ay yung table header
  63.         # + ---------+------+
  64.         # | name     | value|
  65.         # + ---------+------+
  66.         table1_corner = f'+{"-" * longest_info}+{"-" * longest_values}+'
  67.         print(table1_corner)
  68.         print(f'|{row_builder(" Name", longest_info)}|{row_builder(" Value", longest_values)}|')
  69.         print(table1_corner)
  70.         # [6] etong for loop, dito yung pag print ng rows
  71.         for i in range(0, len(info)):
  72.             print(f'|{row_builder(info[i], longest_info)}|{row_builder(values[i], longest_values)}|')
  73.         print(table1_corner)
  74.         # [7] table2 eto yung second table na may directions at distance na kinuha sa [1] at [2], same logic ng [5]
  75.         table2_corner = f'+{"-" * longest_kms}+{"-" * longest_narrative_str}+'
  76.         print(table2_corner)
  77.         print(f'|{row_builder(" Distance", longest_kms)}|{row_builder(" Directions", longest_narrative_str)}|')
  78.         print(table2_corner)
  79.         # same ng [6]
  80.         for i in range(0, len(kms)):
  81.             print(f'|{row_builder(kms[i], longest_kms)}|{row_builder(narratives[i], longest_narrative_str)}|')
  82.         print(table2_corner)
  83.     elif json_status == 402:
  84.         show_error(json_status, "Invalid user inputs from one or both location")
  85.     elif json_status == 611:
  86.         show_error(json_status, "Missing an entry for one or both locations")
  87.     else:
  88.         print('************************************************************')
  89.         print(f'FOr Status Code: {str(json_status)}; Refer to:')
  90.         print('https://developer.mapquest.com/documentation/directions-api/status-codes')
  91.         print('*************************************************************\n')
Advertisement
Add Comment
Please, Sign In to add comment