Currently your code is not re-useable. To make it re-useable you should move the logic inside a function.
To do this the function we will have two functions here: _get_data_from_api
and get_current_iss_location
. Former gets the data from API and latter one passes that data to LatLon
class and returns its instance.
The advantage of having two functions here is that the data fetching part and processing part are now isolated and each function is doing a specific thing. Plus having two isolated functions also allows us to test them easily, for example _get_data_from_api
function can easily be mocked to return some data in tests and that way our tests won't rely on this external API.
For basic performance improvement we will be using a global session here to re-use previous connections.
Having a separate class LatLon
to represent data allows to access the data later on and it can also have other methods that can be used later to do other stuff.
from time import strftime, localtime
import requests
session = requests.Session()
class LatLong:
def __init__(self, latitude, longitude, timestamp):
self.latitude = float(latitude)
self.longitude = float(longitude)
self.time = strftime('%T', localtime(timestamp))
@property
def latitude_hemishere(self):
return 'N' if self.latitude > 0 else 'S'
@property
def longitude_hemisphere(self):
return 'E' if self.longitude > 0 else 'W'
def __str__(self):
return (
"<Latitude: {self.latitude}° {self.latitude_hemishere} |"
" Longitude: {self.longitude}° {self.longitude_hemisphere} at {self.time}>").format(self=self)
__repr__ = __str__
def pprint(self):
print('International Space Station position @ {}'.format(self.time))
print('Latitude: {self.latitude}° {self.latitude_hemishere}'.format(self=self))
print('Longitude: {self.longitude}° {self.longitude_hemisphere}'.format(self=self))
def _get_data_from_api():
response = session.get('http://api.open-notify.org/iss-now.json')
response.raise_for_status()
return response.json()
def get_current_iss_location():
data = _get_data_from_api()
iss_position = data['iss_position']
return LatLong(iss_position['latitude'], iss_position['longitude'], data['timestamp'])
if __name__ == '__main__':
get_current_iss_location().pprint()
Now running the module directly will result in:
International Space Station position @ 21:14:51
Latitude: -51.518° S
Longitude: -93.6953° W
We can also import the function in other modules and get the values:
>>> loc = get_current_iss_location()
>>> loc
<Latitude: -51.616° S | Longitude: -89.694° W at 21:15:31>
>>> loc.latitude
-51.616
>>> loc.longitude
-89.694
>>> loc.time
'21:15:31'
>>> loc.pprint()
International Space Station position @ 21:15:31
Latitude: -51.616° S
Longitude: -89.694° W