· 6 years ago · Apr 01, 2019, 04:16 PM
1I've set up a flask application that checks an API for train information via parameters passed in the URL.
2
3The main lookup part of the function is in this function:
4```
5train_service_data = {}
6train_station_data = {}
7
8dest = 0
9origin = 0
10mytimes = 0
11myurl = 0
12
13
14def checker():
15 global mytrains # modifies the global copy of mytrains otherwise a new variable is created
16 global myurl
17 global mytimes
18 # myurl = f"http://huxley.apphb.com/all/{origin}/to/{dest}/{mytimes}"
19 response = requests.get(myurl, params={"accessToken": SECRET_KEY})
20 response.raise_for_status() # this makes an error if something failed
21 data1 = response.json()
22 mytrains['departure'] = str(data1['crs'])
23 mytrains['arrival'] = str(data1['filtercrs'])
24 try:
25 found_service = 0
26 for index, service in enumerate(data1['trainServices']): # indexes data for pulling of previous values
27 if service['std'].replace(':', '') in mytimes:
28 found_service += 1
29 train = SimpleNamespace(
30 serviceID=str(service['serviceID']),
31 arrival_time=str(service['std']),
32 estimated_arrival=str(service['etd']),
33 status='On time'
34 )
35 prior_service = data1['trainServices'][index - 1]
36 if train.estimated_arrival == 'Cancelled':
37 train.status = 'Cancelled'
38 train.alternate_service = str(prior_service['std'])
39 train.alternate_status = str(prior_service['etd'])
40 elif train.estimated_arrival != 'On time':
41 train.status = 'Delayed'
42 write_index = index
43 for i, v in mytrains.items():
44 if isinstance(v, dict) and v['arrival_time'] == train.arrival_time:
45 write_index = i
46 mytrains[write_index] = train.__dict__
47 elif found_service == 0: # if no service is found
48 mytrains['state'] = 'The services currently available are not specified in user_time.'
49 except (TypeError, AttributeError) as error:
50 mytrains['errorMessage'] = 'There is no train service data'
51 try:
52 NRCCRegex = re.compile('^(.*?)[\.!\?](?:\s|$)') # regex pulls all characters until hitting a . or ! or ?
53 myline = NRCCRegex.search(data1['nrccMessages'][0]['value']) # regex searches through nrccMessages
54 mytrains['nrcc'] = myline.group(1) # prints parsed NRCC message
55 except (TypeError, AttributeError) as error: # tuple catches multiple errors, AttributeError for None value
56 mytrains['nrcc'] = 'No NRCC'
57 return mytrains
58
59```
60
61This then gets split into the location and actual services messages via the following two functions:
62
63```
64def time_trains_services(): # splits data into train services lookup
65 global train_service_data
66 train_service_data = [j for i, j in mytrains.items() if isinstance(j, dict)] # grabs train service data into dict
67 return train_service_data
68
69
70def time_trains_location(): # splits data into crs, filtercrs and nrcc queries
71 global train_station_data
72 train_station_data = {i: j for i, j in mytrains.items() if not isinstance(j, dict)} # grabs [0] data into separate dict
73 return train_station_data
74```