Script to load the ISS location and data












12












$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)









share|improve this question











$endgroup$

















    12












    $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)









    share|improve this question











    $endgroup$















      12












      12








      12


      1



      $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)









      share|improve this question











      $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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      Graipher

      26.2k54092




      26.2k54092










      asked yesterday









      dsahariadsaharia

      835




      835






















          1 Answer
          1






          active

          oldest

          votes


















          9












          $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-strings (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()





          share|improve this answer











          $endgroup$









          • 2




            $begingroup$
            I would add a function "get_data(url)" where you can pass the url and it returns a response
            $endgroup$
            – Margon
            yesterday






          • 1




            $begingroup$
            @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
            $endgroup$
            – Graipher
            yesterday






          • 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
            yesterday






          • 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
            yesterday











          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
          });


          }
          });














          draft saved

          draft discarded


















          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









          9












          $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-strings (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()





          share|improve this answer











          $endgroup$









          • 2




            $begingroup$
            I would add a function "get_data(url)" where you can pass the url and it returns a response
            $endgroup$
            – Margon
            yesterday






          • 1




            $begingroup$
            @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
            $endgroup$
            – Graipher
            yesterday






          • 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
            yesterday






          • 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
            yesterday
















          9












          $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-strings (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()





          share|improve this answer











          $endgroup$









          • 2




            $begingroup$
            I would add a function "get_data(url)" where you can pass the url and it returns a response
            $endgroup$
            – Margon
            yesterday






          • 1




            $begingroup$
            @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
            $endgroup$
            – Graipher
            yesterday






          • 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
            yesterday






          • 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
            yesterday














          9












          9








          9





          $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-strings (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()





          share|improve this answer











          $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-strings (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()






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered yesterday









          GraipherGraipher

          26.2k54092




          26.2k54092








          • 2




            $begingroup$
            I would add a function "get_data(url)" where you can pass the url and it returns a response
            $endgroup$
            – Margon
            yesterday






          • 1




            $begingroup$
            @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
            $endgroup$
            – Graipher
            yesterday






          • 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
            yesterday






          • 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
            yesterday














          • 2




            $begingroup$
            I would add a function "get_data(url)" where you can pass the url and it returns a response
            $endgroup$
            – Margon
            yesterday






          • 1




            $begingroup$
            @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
            $endgroup$
            – Graipher
            yesterday






          • 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
            yesterday






          • 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
            yesterday








          2




          2




          $begingroup$
          I would add a function "get_data(url)" where you can pass the url and it returns a response
          $endgroup$
          – Margon
          yesterday




          $begingroup$
          I would add a function "get_data(url)" where you can pass the url and it returns a response
          $endgroup$
          – Margon
          yesterday




          1




          1




          $begingroup$
          @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
          $endgroup$
          – Graipher
          yesterday




          $begingroup$
          @Margon True, I was on edge whether or not I would add it, since it is only repeated once...
          $endgroup$
          – Graipher
          yesterday




          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
          yesterday




          $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
          yesterday




          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
          yesterday




          $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
          yesterday


















          draft saved

          draft discarded




















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          數位音樂下載

          When can things happen in Etherscan, such as the picture below?

          格利澤436b