Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix all flake8 errors #183

Merged
merged 3 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 49 additions & 35 deletions pittapi/course.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,28 @@
from typing import NamedTuple

# https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/WEBLIB_HCX_CM.H_CLASS_SEARCH.FieldFormula.IScript_ClassSearch?institution=UPITT&term=2244&date_from=&date_thru=&subject=CS&subject_like=&catalog_nbr=&time_range=&days=&campus=PIT&location=&x_acad_career=UGRD&acad_group=&rqmnt_designtn=&instruction_mode=&keyword=&class_nbr=&acad_org=&enrl_stat=O&crse_attr=&crse_attr_value=&instructor_name=&instr_first_name=&session_code=&units=&trigger_search=&page=1
SUBJECTS_API = "https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/WEBLIB_HCX_CM.H_COURSE_CATALOG.FieldFormula.IScript_CatalogSubjects?institution=UPITT"
SUBJECT_COURSES_API = "https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/WEBLIB_HCX_CM.H_COURSE_CATALOG.FieldFormula.IScript_SubjectCourses?institution=UPITT&subject={subject}"
COURSE_DETAIL_API = "https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/WEBLIB_HCX_CM.H_COURSE_CATALOG.FieldFormula.IScript_CatalogCourseDetails?institution=UPITT&course_id={id}&effdt=2018-06-30&crse_offer_nbr=1&use_catalog_print=Y"
COURSE_SECTIONS_API = "https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/WEBLIB_HCX_CM.H_BROWSE_CLASSES.FieldFormula.IScript_BrowseSections?institution=UPITT&campus=&location=&course_id={id}&institution=UPITT&term={term}&crse_offer_nbr=1"
SECTION_DETAILS_API = "https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/WEBLIB_HCX_CM.H_CLASS_SEARCH.FieldFormula.IScript_ClassDetails?institution=UPITT&term={term}&class_nbr={id}"
SUBJECTS_API = (
"https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/"
"WEBLIB_HCX_CM.H_COURSE_CATALOG.FieldFormula.IScript_CatalogSubjects?institution=UPITT"
)
SUBJECT_COURSES_API = (
"https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/"
"WEBLIB_HCX_CM.H_COURSE_CATALOG.FieldFormula.IScript_SubjectCourses?institution=UPITT&subject={subject}"
)
COURSE_DETAIL_API = (
"https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/"
"WEBLIB_HCX_CM.H_COURSE_CATALOG.FieldFormula.IScript_CatalogCourseDetails?institution=UPITT&course_id={id}"
"&effdt=2018-06-30&crse_offer_nbr=1&use_catalog_print=Y"
)
COURSE_SECTIONS_API = (
"https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/"
"WEBLIB_HCX_CM.H_BROWSE_CLASSES.FieldFormula.IScript_BrowseSections?institution=UPITT&campus=&location=&course_id={id}"
"&institution=UPITT&term={term}&crse_offer_nbr=1"
)
SECTION_DETAILS_API = (
"https://pitcsprd.csps.pitt.edu/psc/pitcsprd/EMPLOYEE/SA/s/"
"WEBLIB_HCX_CM.H_CLASS_SEARCH.FieldFormula.IScript_ClassDetails?institution=UPITT&term={term}&class_nbr={id}"
)
# id -> unique course ID, not to be confused with course code (for instance, CS 0007 has code 105611)
# career -> for example, UGRD (undergraduate)

Expand Down Expand Up @@ -151,27 +168,25 @@ def get_course_details(term: str | int, subject: str, course: str | int) -> Cour

components = None
if "components" in json_response and len(json_response["components"]) != 0:
components = []
for component in json_response["components"]:
components.append(
Component(
component=component["descr"],
required=True if component["optional"] == "N" else False,
)
components = [
Component(
component=component["descr"],
required=True if component["optional"] == "N" else False,
)
for component in json_response["components"]
]

attributes = None
if "attributes" in json_response and len(json_response["attributes"]) != 0:
attributes = []
for attribute in json_response["attributes"]:
attributes.append(
Attribute(
attribute=attribute["crse_attribute"],
attribute_description=attribute["crse_attribute_descr"],
value=attribute["crse_attribute_value"],
value_description=attribute["crse_attribute_value_descr"],
)
attributes = [
Attribute(
attribute=attribute["crse_attribute"],
attribute_description=attribute["crse_attribute_descr"],
value=attribute["crse_attribute_value"],
value_description=attribute["crse_attribute_value_descr"],
)
for attribute in json_response["attributes"]
]

sections = []
for section in json_response_details["sections"]:
Expand All @@ -183,24 +198,23 @@ def get_course_details(term: str | int, subject: str, course: str | int) -> Cour

instructors = None
if len(section["instructors"]) != 0 and section["instructors"][0] != "To be Announced":
instructors = []
for instructor in section["instructors"]:
instructors.append(Instructor(name=instructor["name"], email=instructor["email"]))
instructors = [
Instructor(name=instructor["name"], email=instructor["email"]) for instructor in section["instructors"]
]

meetings = None
if len(section["meetings"]) != 0:
meetings = []
for meeting in section["meetings"]:
meetings.append(
Meeting(
days=meeting["days"],
start_time=meeting["start_time"],
end_time=meeting["end_time"],
start_date=meeting["start_dt"],
end_date=meeting["end_dt"],
instructors=[Instructor(name=meeting["instructor"])],
)
meetings = [
Meeting(
days=meeting["days"],
start_time=meeting["start_time"],
end_time=meeting["end_time"],
start_date=meeting["start_dt"],
end_date=meeting["end_dt"],
instructors=[Instructor(name=meeting["instructor"])],
)
for meeting in section["meetings"]
]

sections.append(
Section(
Expand Down
78 changes: 35 additions & 43 deletions pittapi/dining.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,16 @@
"CAFE 1923",
}

LOCATIONS_URL = "https://api.dineoncampus.com/v1/locations/status?site_id=5e6fcc641ca48e0cacd93b04&platform="
HOURS_URL = "https://api.dineoncampus.com/v1/locations/weekly_schedule?site_id=5e6fcc641ca48e0cacd93b04&date=%22{date_str}%22"
PERIODS_URL = "https://api.dineoncampus.com/v1/location/{location_id}/periods?platform=0&date={date_str}"
MENU_URL = "https://api.dineoncampus.com/v1/location/{location_id}/periods/{period_id}?platform=0&date={date_str}"


def get_locations() -> dict[str, Any]:
"""Gets data about all dining locations"""

url = "https://api.dineoncampus.com/v1/locations/status?site_id=5e6fcc641ca48e0cacd93b04&platform="

resp = requests.get(
url,
headers=REQUEST_HEADERS,
)

resp = requests.get(LOCATIONS_URL, headers=REQUEST_HEADERS)
locations = json.loads(resp.content)["locations"]

dining_locations = {location["name"].upper(): location for location in locations}

return dining_locations
Expand All @@ -87,76 +84,71 @@ def get_location_hours(location_name: str, date: datetime) -> dict[str, Any]:
- date must be in YYYY,MM,DD format, will return data on current day if None
"""

if location_name != None and location_name.upper() not in LOCATIONS:
if location_name is not None and location_name.upper() not in LOCATIONS:
raise ValueError("Invalid Dining Location")

if date == None:
if date is None:
date = datetime.now()

date_str = date.strftime("%Y-%m-%d")

url = f"https://api.dineoncampus.com/v1/locations/weekly_schedule?site_id=5e6fcc641ca48e0cacd93b04&date=%22{date_str}%22"

resp = requests.get(url, headers=REQUEST_HEADERS)
resp = requests.get(
HOURS_URL.format(date_str=date_str),
headers=REQUEST_HEADERS,
)

if resp.status_code == 502:
raise ValueError("Invalid Date")

locations = json.loads(resp.content)["the_locations"]

hours = {}
if location_name is None:
hours = {
location["name"]: day["hours"] for location in locations for day in location["week"] if day["date"] == date_str
}
return hours

if location_name == None:
for location in locations:
for day in location["week"]:
if day["date"] == date_str:
hours[location["name"]] = day["hours"]
else:
for location in locations:
if location["name"].upper() == location_name.upper():
for day in location["week"]:
if day["date"] == date_str:
hours[location["name"]] = day["hours"]
break
for location in locations:
if location["name"].upper() == location_name.upper():
hours = {location["name"]: day["hours"] for day in location["week"] if day["date"] == date_str}
return hours

return hours
return {}


def get_location_menu(location: str, date: datetime, period_name: str):
"""Returns menu data for given dining location on given day/period
-period_name used for locations with different serving periods(i.e. 'Breakfast','Lunch','Dinner','Late Night')
- None -> Returns menu for first(or only) period at location"""
- period_name used for locations with different serving periods(i.e. 'Breakfast','Lunch','Dinner','Late Night')
- None -> Returns menu for first(or only) period at location
"""

if location.upper() not in LOCATIONS:
raise ValueError("Invalid Dining Location")

if date == None:
if date is None:
date = datetime.today()

date_str = date.strftime("%y-%m-%d")

location_id = get_locations()[location.upper()]["id"]

periods_url = f"https://api.dineoncampus.com/v1/location/{location_id}/periods?platform=0&date={date_str}"

periods_resp = requests.get(periods_url, headers=REQUEST_HEADERS)
periods_resp = requests.get(
PERIODS_URL.format(location_id=location_id, date_str=date_str),
headers=REQUEST_HEADERS,
)

if periods_resp.status_code == 502:
raise ValueError("Invalid Date")

periods = json.loads(periods_resp.content)["periods"]

if period_name == None or len(periods) == 1:
if period_name is None or len(periods) == 1:
period_id = periods[0]["id"]
else:
for period in periods:
if period["name"].lower() == period_name.lower():
period_id = period["id"]

menu_url = f"https://api.dineoncampus.com/v1/location/{location_id}/periods/{period_id}?platform=0&date={date_str}"

menu_resp = requests.get(menu_url, headers=REQUEST_HEADERS)

menu_resp = requests.get(
MENU_URL.format(location_id=location_id, period_id=period_id, date_str=date_str),
headers=REQUEST_HEADERS,
)
menu = json.loads(menu_resp.content)["menu"]

return menu
4 changes: 2 additions & 2 deletions pittapi/laundry.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from typing import Any


BASE_URL = "https://www.laundryview.com/api/currentRoomData?school_desc_key=197&location={}"
BASE_URL = "https://www.laundryview.com/api/currentRoomData?school_desc_key=197&location={location}"

LOCATION_LOOKUP = {
"TOWERS": "2430136",
Expand All @@ -40,7 +40,7 @@
def _get_laundry_info(building_name: str) -> Any:
"""Returns JSON object of laundry view webpage"""
building_name = building_name.upper()
url = BASE_URL.format(LOCATION_LOOKUP[building_name])
url = BASE_URL.format(location=LOCATION_LOOKUP[building_name])
response = requests.get(url)
info = response.json()
return info
Expand Down
22 changes: 12 additions & 10 deletions pittapi/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@

LIBRARY_URL = (
"https://pitt.primo.exlibrisgroup.com/primaws/rest/pub/pnxs"
"?acTriggered=false&blendFacetsSeparately=false"
"&citationTrailFilterByAvailability=true&disableCache=false&getMore=0"
"&inst=01PITT_INST&isCDSearch=false&lang=en&limit=10&newspapersActive=false"
"&newspapersSearch=false&offset=0&otbRanking=false&pcAvailability=false"
"&qExclude=&qInclude=&rapido=false&refEntryActive=false&rtaLinks=true"
"&scope=MyInst_and_CI&searchInFulltextUserSelection=false&skipDelivery=Y"
"&sort=rank&tab=Everything&vid=01PITT_INST:01PITT_INST"
"?acTriggered=false&blendFacetsSeparately=false&citationTrailFilterByAvailability=true&disableCache=false&getMore=0"
"&inst=01PITT_INST&isCDSearch=false&lang=en&limit=10&newspapersActive=false&newspapersSearch=false&offset=0"
"&otbRanking=false&pcAvailability=false&qExclude=&qInclude=&rapido=false&refEntryActive=false&rtaLinks=true"
"&scope=MyInst_and_CI&searchInFulltextUserSelection=false&skipDelivery=Y&sort=rank&tab=Everything"
"&vid=01PITT_INST:01PITT_INST"
)

STUDY_ROOMS_URL = "https://pitt.libcal.com/spaces/bookings/search?lid=917&gid=1558&eid=0&seat=0&d=1&customDate=&q=&daily=0&draw=1&order%5B0%5D%5Bcolumn%5D=1&order%5B0%5D%5Bdir%5D=asc&start=0&length=25&search%5Bvalue%5D=&_=1717907260661"
STUDY_ROOMS_URL = (
"https://pitt.libcal.com/spaces/bookings/search"
"?lid=917&gid=1558&eid=0&seat=0&d=1&customDate=&q=&daily=0&draw=1&order%5B0%5D%5Bcolumn%5D=1&order%5B0%5D%5Bdir%5D=asc"
"&start=0&length=25&search%5Bvalue%5D=&_=1717907260661"
)


QUERY_START = "&q=any,contains,"
Expand Down Expand Up @@ -148,15 +150,15 @@ def hillman_total_reserved() -> dict[str, int]:


def reserved_hillman_times() -> list[dict[str, str | list[str]]]:
"""Returns a list of dictionaries of reserved rooms of the Hillman with their respective times"""
"""Returns a list of dictionaries of reserved rooms in Hillman with their respective times"""
resp = requests.get(STUDY_ROOMS_URL)
resp = resp.json()
data = resp["data"]

if data is None:
return []

# Note: there can be multiple reservations in the same room, hence why we must use a list of maps, and cannot just use a singular map
# Note: there can be multiple reservations in the same room, so we must use a list of maps and not a singular map
bookings = [
{
"Room": reservation["itemName"],
Expand Down
33 changes: 14 additions & 19 deletions pittapi/shuttle.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,44 +20,39 @@
import requests
from typing import Any


API_KEY = "8882812681"
VEHICLE_POINTS_URL = "http://www.pittshuttle.com/Services/JSONPRelay.svc/GetMapVehiclePoints"
ARRIVAL_TIMES_URL = "http://www.pittshuttle.com/Services/JSONPRelay.svc/GetRouteStopArrivals"
STOP_ESTIMATES_URL = "http://www.pittshuttle.com/Services/JSONPRelay.svc/GetVehicleRouteStopEstimates"
ROUTES_URL = "http://www.pittshuttle.com/Services/JSONPRelay.svc/GetRoutesForMap"

sess = requests.session()


def get_map_vehicle_points(api_key: str = "8882812681") -> dict[str, Any]:
def get_map_vehicle_points(api_key: str = API_KEY) -> dict[str, Any]:
"""Return the map location for all active vehicles."""
payload = {"ApiKey": api_key}
response = sess.get(
"http://www.pittshuttle.com/Services/JSONPRelay.svc/GetMapVehiclePoints",
params=payload,
)
response = sess.get(VEHICLE_POINTS_URL, params=payload)
return response.json()


def get_route_stop_arrivals(api_key: str = "8882812681", times_per_stop: int = 1) -> dict[str, Any]:
def get_route_stop_arrivals(api_key: str = API_KEY, times_per_stop: int = 1) -> dict[str, Any]:
"""Return stop arrival times for all vehicles."""
payload = {"ApiKey": api_key, "TimesPerStopString": times_per_stop}
response = sess.get(
"http://www.pittshuttle.com/Services/JSONPRelay.svc/GetRouteStopArrivals",
params=payload,
)
response = sess.get(ARRIVAL_TIMES_URL, params=payload)
return response.json()


def get_vehicle_route_stop_estimates(vehicle_id: str, quantity: int = 2) -> dict[str, Any]:
"""Return {quantity} stop estimates for all active vehicles."""
payload = {"vehicleIdStrings": vehicle_id, "quantity": str(quantity)}
response = sess.get(
"http://www.pittshuttle.com/Services/JSONPRelay.svc/GetVehicleRouteStopEstimates",
params=payload,
)
response = sess.get(STOP_ESTIMATES_URL, params=payload)
return response.json()


def get_routes(api_key: str = "8882812681") -> dict[str, Any]:
def get_routes(api_key: str = API_KEY) -> dict[str, Any]:
"""Return the routes with Vehicle Route Name, Vehicle ID, and all stops, etc."""
payload = {"ApiKey": api_key}
response = sess.get(
"http://www.pittshuttle.com/Services/JSONPRelay.svc/GetRoutesForMap",
params=payload,
)
response = sess.get(ROUTES_URL, params=payload)
return response.json()
12 changes: 1 addition & 11 deletions tests/course_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,7 @@

from pittapi import course

from pittapi.course import (
Attribute,
Component,
Course,
CourseDetails,
Instructor,
Meeting,
Section,
SectionDetails,
Subject,
)
from pittapi.course import Attribute, Course, CourseDetails, Instructor, Meeting, Section, SectionDetails, Subject

from tests.mocks.course_mocks import (
mocked_subject_data,
Expand Down
Loading
Loading