Script to load the ISS location and data
$begingroup$
I wrote a script to fetch the location for the ISS using two simple API's. This is my first time writing a python script. Any advice or modifications would be highly appreciated. How is the code review and where are the areas I can Improve upon?
GITHUB LINK: https://github.com/dsaharia/iss_location
import urllib.request # to make requests to the api
import json # to parse the json response
import reverse_geocoder as rg # to get address from location
url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url) # request the api, returns a JSON object
json_result = json.loads(response.read()) # read the JSON object
# Separate different values based on keys.
people = json_result['people'] # people currently in space
number_in_space = json_result['number'] # total people in space
print("People in space : ", number_in_space)
print("----NAMES----")
for p in people:
print(p['name'])
# ISS data
iss_url = "http://api.open-notify.org/iss-now.json"
iss_response = urllib.request.urlopen(iss_url)
iss_json_result = json.loads(iss_response.read())
# Store the positions
latitude = iss_json_result['iss_position']['latitude'] # store the latitude
longitude = iss_json_result['iss_position']['longitude']
print("Latitude: ", latitude," -- ", "Longitude: ", longitude)
address = rg.search((latitude, longitude)) # Get the address from location tuple returns a list
address_name = address[0]['name']
address_admin1 = address[0]['admin1']
address_admin2 = address[0]['admin2']
address_cc = address[0]['cc']
print("----Address----")
print(address_name, ", ", address_admin1, address_admin2, address_cc)
python python-3.x api
$endgroup$
add a comment |
$begingroup$
I wrote a script to fetch the location for the ISS using two simple API's. This is my first time writing a python script. Any advice or modifications would be highly appreciated. How is the code review and where are the areas I can Improve upon?
GITHUB LINK: https://github.com/dsaharia/iss_location
import urllib.request # to make requests to the api
import json # to parse the json response
import reverse_geocoder as rg # to get address from location
url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url) # request the api, returns a JSON object
json_result = json.loads(response.read()) # read the JSON object
# Separate different values based on keys.
people = json_result['people'] # people currently in space
number_in_space = json_result['number'] # total people in space
print("People in space : ", number_in_space)
print("----NAMES----")
for p in people:
print(p['name'])
# ISS data
iss_url = "http://api.open-notify.org/iss-now.json"
iss_response = urllib.request.urlopen(iss_url)
iss_json_result = json.loads(iss_response.read())
# Store the positions
latitude = iss_json_result['iss_position']['latitude'] # store the latitude
longitude = iss_json_result['iss_position']['longitude']
print("Latitude: ", latitude," -- ", "Longitude: ", longitude)
address = rg.search((latitude, longitude)) # Get the address from location tuple returns a list
address_name = address[0]['name']
address_admin1 = address[0]['admin1']
address_admin2 = address[0]['admin2']
address_cc = address[0]['cc']
print("----Address----")
print(address_name, ", ", address_admin1, address_admin2, address_cc)
python python-3.x api
$endgroup$
add a comment |
$begingroup$
I wrote a script to fetch the location for the ISS using two simple API's. This is my first time writing a python script. Any advice or modifications would be highly appreciated. How is the code review and where are the areas I can Improve upon?
GITHUB LINK: https://github.com/dsaharia/iss_location
import urllib.request # to make requests to the api
import json # to parse the json response
import reverse_geocoder as rg # to get address from location
url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url) # request the api, returns a JSON object
json_result = json.loads(response.read()) # read the JSON object
# Separate different values based on keys.
people = json_result['people'] # people currently in space
number_in_space = json_result['number'] # total people in space
print("People in space : ", number_in_space)
print("----NAMES----")
for p in people:
print(p['name'])
# ISS data
iss_url = "http://api.open-notify.org/iss-now.json"
iss_response = urllib.request.urlopen(iss_url)
iss_json_result = json.loads(iss_response.read())
# Store the positions
latitude = iss_json_result['iss_position']['latitude'] # store the latitude
longitude = iss_json_result['iss_position']['longitude']
print("Latitude: ", latitude," -- ", "Longitude: ", longitude)
address = rg.search((latitude, longitude)) # Get the address from location tuple returns a list
address_name = address[0]['name']
address_admin1 = address[0]['admin1']
address_admin2 = address[0]['admin2']
address_cc = address[0]['cc']
print("----Address----")
print(address_name, ", ", address_admin1, address_admin2, address_cc)
python python-3.x api
$endgroup$
I wrote a script to fetch the location for the ISS using two simple API's. This is my first time writing a python script. Any advice or modifications would be highly appreciated. How is the code review and where are the areas I can Improve upon?
GITHUB LINK: https://github.com/dsaharia/iss_location
import urllib.request # to make requests to the api
import json # to parse the json response
import reverse_geocoder as rg # to get address from location
url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url) # request the api, returns a JSON object
json_result = json.loads(response.read()) # read the JSON object
# Separate different values based on keys.
people = json_result['people'] # people currently in space
number_in_space = json_result['number'] # total people in space
print("People in space : ", number_in_space)
print("----NAMES----")
for p in people:
print(p['name'])
# ISS data
iss_url = "http://api.open-notify.org/iss-now.json"
iss_response = urllib.request.urlopen(iss_url)
iss_json_result = json.loads(iss_response.read())
# Store the positions
latitude = iss_json_result['iss_position']['latitude'] # store the latitude
longitude = iss_json_result['iss_position']['longitude']
print("Latitude: ", latitude," -- ", "Longitude: ", longitude)
address = rg.search((latitude, longitude)) # Get the address from location tuple returns a list
address_name = address[0]['name']
address_admin1 = address[0]['admin1']
address_admin2 = address[0]['admin2']
address_cc = address[0]['cc']
print("----Address----")
print(address_name, ", ", address_admin1, address_admin2, address_cc)
python python-3.x api
python python-3.x api
edited Mar 19 at 14:22
Graipher
26.3k54092
26.3k54092
asked Mar 19 at 9:45
dsahariadsaharia
835
835
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
Not bad for a first Python script!
In general, you can greatly benefit from giving parts of your code names, by encapsulating them in functions. This makes it also re-usable and let's you add a docstring
giving more detail on what this function does.
If you add a main
function which you call under a if __name__ == "__main__":
guard you can also import these functions from another script without all of your code running.
Instead of urllib.request
, you can use the requests
module, it even has a method to directly return a JSON object.
While it is nice that the astronauts response contains the number of astronauts in space, you could get the same information from calling len(people)
, which is $mathcal{O}(1)$ for Python lists.
Familiarize yourself with f-string
s (Python 3.6+). They are a nice and compact way to write formatted strings, since they can contain arbitrary Python expressions (I used it for the address here).
import requests
import reverse_geocoder
def get_json(url):
"""Retrieve JSON object from url.
Raises an exception if connection fails.
"""
response = requests.get(url)
response.raise_for_status() # make sure an exception is raised if something goes wrong
return response.json()
def get_astronauts():
"""Returns a list of all people currently in space"""
url = "http://api.open-notify.org/astros.json"
return get_json(url)['people']
def get_iss_location():
"""Returns the current latitude and longitude of the ISS"""
url = "http://api.open-notify.org/iss-now.json"
position = get_json(url)['iss_position']
return position['latitude'], position['longitude']
def get_address(position):
"""Do a reverse lookup getting the closest address to a given position"""
return reverse_geocoder.search(position)[0]
def main():
astronauts_in_space = get_astronauts()
print("People in space : ", len(astronauts_in_space))
print("----NAMES----")
for astronaut in astronauts_in_space:
print(astronaut['name'])
iss_position = get_iss_location()
print("Latitude: ", position[0]," -- ", "Longitude: ", position[1])
address = get_address(iss_position)
print("----Address----")
print(f"{address['name']}, {address['admin1']} {address['admin2']} {address['cc']}")
if __name__ == "__main__":
main()
$endgroup$
2
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
1
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
1
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by.json()
does not have araise_for_status
method).
$endgroup$
– Graipher
Mar 19 at 14:00
3
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215737%2fscript-to-load-the-iss-location-and-data%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Not bad for a first Python script!
In general, you can greatly benefit from giving parts of your code names, by encapsulating them in functions. This makes it also re-usable and let's you add a docstring
giving more detail on what this function does.
If you add a main
function which you call under a if __name__ == "__main__":
guard you can also import these functions from another script without all of your code running.
Instead of urllib.request
, you can use the requests
module, it even has a method to directly return a JSON object.
While it is nice that the astronauts response contains the number of astronauts in space, you could get the same information from calling len(people)
, which is $mathcal{O}(1)$ for Python lists.
Familiarize yourself with f-string
s (Python 3.6+). They are a nice and compact way to write formatted strings, since they can contain arbitrary Python expressions (I used it for the address here).
import requests
import reverse_geocoder
def get_json(url):
"""Retrieve JSON object from url.
Raises an exception if connection fails.
"""
response = requests.get(url)
response.raise_for_status() # make sure an exception is raised if something goes wrong
return response.json()
def get_astronauts():
"""Returns a list of all people currently in space"""
url = "http://api.open-notify.org/astros.json"
return get_json(url)['people']
def get_iss_location():
"""Returns the current latitude and longitude of the ISS"""
url = "http://api.open-notify.org/iss-now.json"
position = get_json(url)['iss_position']
return position['latitude'], position['longitude']
def get_address(position):
"""Do a reverse lookup getting the closest address to a given position"""
return reverse_geocoder.search(position)[0]
def main():
astronauts_in_space = get_astronauts()
print("People in space : ", len(astronauts_in_space))
print("----NAMES----")
for astronaut in astronauts_in_space:
print(astronaut['name'])
iss_position = get_iss_location()
print("Latitude: ", position[0]," -- ", "Longitude: ", position[1])
address = get_address(iss_position)
print("----Address----")
print(f"{address['name']}, {address['admin1']} {address['admin2']} {address['cc']}")
if __name__ == "__main__":
main()
$endgroup$
2
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
1
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
1
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by.json()
does not have araise_for_status
method).
$endgroup$
– Graipher
Mar 19 at 14:00
3
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
add a comment |
$begingroup$
Not bad for a first Python script!
In general, you can greatly benefit from giving parts of your code names, by encapsulating them in functions. This makes it also re-usable and let's you add a docstring
giving more detail on what this function does.
If you add a main
function which you call under a if __name__ == "__main__":
guard you can also import these functions from another script without all of your code running.
Instead of urllib.request
, you can use the requests
module, it even has a method to directly return a JSON object.
While it is nice that the astronauts response contains the number of astronauts in space, you could get the same information from calling len(people)
, which is $mathcal{O}(1)$ for Python lists.
Familiarize yourself with f-string
s (Python 3.6+). They are a nice and compact way to write formatted strings, since they can contain arbitrary Python expressions (I used it for the address here).
import requests
import reverse_geocoder
def get_json(url):
"""Retrieve JSON object from url.
Raises an exception if connection fails.
"""
response = requests.get(url)
response.raise_for_status() # make sure an exception is raised if something goes wrong
return response.json()
def get_astronauts():
"""Returns a list of all people currently in space"""
url = "http://api.open-notify.org/astros.json"
return get_json(url)['people']
def get_iss_location():
"""Returns the current latitude and longitude of the ISS"""
url = "http://api.open-notify.org/iss-now.json"
position = get_json(url)['iss_position']
return position['latitude'], position['longitude']
def get_address(position):
"""Do a reverse lookup getting the closest address to a given position"""
return reverse_geocoder.search(position)[0]
def main():
astronauts_in_space = get_astronauts()
print("People in space : ", len(astronauts_in_space))
print("----NAMES----")
for astronaut in astronauts_in_space:
print(astronaut['name'])
iss_position = get_iss_location()
print("Latitude: ", position[0]," -- ", "Longitude: ", position[1])
address = get_address(iss_position)
print("----Address----")
print(f"{address['name']}, {address['admin1']} {address['admin2']} {address['cc']}")
if __name__ == "__main__":
main()
$endgroup$
2
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
1
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
1
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by.json()
does not have araise_for_status
method).
$endgroup$
– Graipher
Mar 19 at 14:00
3
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
add a comment |
$begingroup$
Not bad for a first Python script!
In general, you can greatly benefit from giving parts of your code names, by encapsulating them in functions. This makes it also re-usable and let's you add a docstring
giving more detail on what this function does.
If you add a main
function which you call under a if __name__ == "__main__":
guard you can also import these functions from another script without all of your code running.
Instead of urllib.request
, you can use the requests
module, it even has a method to directly return a JSON object.
While it is nice that the astronauts response contains the number of astronauts in space, you could get the same information from calling len(people)
, which is $mathcal{O}(1)$ for Python lists.
Familiarize yourself with f-string
s (Python 3.6+). They are a nice and compact way to write formatted strings, since they can contain arbitrary Python expressions (I used it for the address here).
import requests
import reverse_geocoder
def get_json(url):
"""Retrieve JSON object from url.
Raises an exception if connection fails.
"""
response = requests.get(url)
response.raise_for_status() # make sure an exception is raised if something goes wrong
return response.json()
def get_astronauts():
"""Returns a list of all people currently in space"""
url = "http://api.open-notify.org/astros.json"
return get_json(url)['people']
def get_iss_location():
"""Returns the current latitude and longitude of the ISS"""
url = "http://api.open-notify.org/iss-now.json"
position = get_json(url)['iss_position']
return position['latitude'], position['longitude']
def get_address(position):
"""Do a reverse lookup getting the closest address to a given position"""
return reverse_geocoder.search(position)[0]
def main():
astronauts_in_space = get_astronauts()
print("People in space : ", len(astronauts_in_space))
print("----NAMES----")
for astronaut in astronauts_in_space:
print(astronaut['name'])
iss_position = get_iss_location()
print("Latitude: ", position[0]," -- ", "Longitude: ", position[1])
address = get_address(iss_position)
print("----Address----")
print(f"{address['name']}, {address['admin1']} {address['admin2']} {address['cc']}")
if __name__ == "__main__":
main()
$endgroup$
Not bad for a first Python script!
In general, you can greatly benefit from giving parts of your code names, by encapsulating them in functions. This makes it also re-usable and let's you add a docstring
giving more detail on what this function does.
If you add a main
function which you call under a if __name__ == "__main__":
guard you can also import these functions from another script without all of your code running.
Instead of urllib.request
, you can use the requests
module, it even has a method to directly return a JSON object.
While it is nice that the astronauts response contains the number of astronauts in space, you could get the same information from calling len(people)
, which is $mathcal{O}(1)$ for Python lists.
Familiarize yourself with f-string
s (Python 3.6+). They are a nice and compact way to write formatted strings, since they can contain arbitrary Python expressions (I used it for the address here).
import requests
import reverse_geocoder
def get_json(url):
"""Retrieve JSON object from url.
Raises an exception if connection fails.
"""
response = requests.get(url)
response.raise_for_status() # make sure an exception is raised if something goes wrong
return response.json()
def get_astronauts():
"""Returns a list of all people currently in space"""
url = "http://api.open-notify.org/astros.json"
return get_json(url)['people']
def get_iss_location():
"""Returns the current latitude and longitude of the ISS"""
url = "http://api.open-notify.org/iss-now.json"
position = get_json(url)['iss_position']
return position['latitude'], position['longitude']
def get_address(position):
"""Do a reverse lookup getting the closest address to a given position"""
return reverse_geocoder.search(position)[0]
def main():
astronauts_in_space = get_astronauts()
print("People in space : ", len(astronauts_in_space))
print("----NAMES----")
for astronaut in astronauts_in_space:
print(astronaut['name'])
iss_position = get_iss_location()
print("Latitude: ", position[0]," -- ", "Longitude: ", position[1])
address = get_address(iss_position)
print("----Address----")
print(f"{address['name']}, {address['admin1']} {address['admin2']} {address['cc']}")
if __name__ == "__main__":
main()
edited Mar 19 at 13:59
answered Mar 19 at 11:54
GraipherGraipher
26.3k54092
26.3k54092
2
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
1
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
1
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by.json()
does not have araise_for_status
method).
$endgroup$
– Graipher
Mar 19 at 14:00
3
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
add a comment |
2
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
1
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
1
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by.json()
does not have araise_for_status
method).
$endgroup$
– Graipher
Mar 19 at 14:00
3
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
2
2
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
$begingroup$
I would add a function "get_data(url)" where you can pass the url and it returns a response
$endgroup$
– Margon
Mar 19 at 13:54
1
1
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
$begingroup$
@Margon True, I was on edge whether or not I would add it, since it is only repeated once...
$endgroup$
– Graipher
Mar 19 at 13:55
1
1
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by
.json()
does not have a raise_for_status
method).$endgroup$
– Graipher
Mar 19 at 14:00
$begingroup$
@Margon This even fixed some bugs (typos and the fact that the dictionary returned by
.json()
does not have a raise_for_status
method).$endgroup$
– Graipher
Mar 19 at 14:00
3
3
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
$begingroup$
Yeah, I quite agree with you, but it's better to give the "best practices", so he can re-use the code if he wants to add more api
$endgroup$
– Margon
Mar 19 at 14:00
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215737%2fscript-to-load-the-iss-location-and-data%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown