Python

Wie können wir helfen?
< Back
You are here:
Drucken

The Python connector gives an easy entry-point to use OKAPI software from within your own python code. We recommend using the package provided via PyPI (see below), as this is updated with every release of OKAPI and actively maintained. If you prefer building your own code, you find the complete source code of the connector on Github. Note though that you have take care of the maintenance yourself.

This complete section is split into the following sections:

  1. Installing and updating the connector using PIP explains you, how to install the OKAPI package on your machine.
  2. Using the connector explains the general features of the connector as well as a short introduction into the error handling.
  3. Running the first calculation gives you a script including an exemplary log-in, sending and getting of the request.

We suggest that you go through the items once to ensure that you do not miss any important information.

Installing and updating the connector using PIP

Note: We recommend to always work in virtual environment with python to avoid cluttering your installation.

The connector has been designed to run with python3. Therefore, make sure that you are using python3 for all commands. Depending on your system configuration, phyton might point to python3 already, or not. So make sure you know what you are using.

To install the OKAPI connector, run (if you are using the powershell on Windows, replace python3 with python.exe):

python3 -m pip install okapi-python-connector

You now have successfully installed the latest version of the okapi-python-connector.

You always should make sure that the version of the python connector matches that of the OKAPI software. You can get the current version of the python connector using pkg_resources in python (again: change python3 into python.exe on Windows):

python3 -c "import pkg_resources; print(pkg_resources.get_distribution('okapi-python-connector').version)"

If you need to upgrade your python connector, run (use python.exe on windows):

python3 -m pip install okapi-python-connector --upgrade

Alternatively, you can get the complete source code of the connector on Github.

Using the connector

Generally, using the connector is very easy. After installing, you have to import the needed functions into your current code. For a first test, import the following functions:

from okapi_pkg.okapi_init import okapi_init
from okapi_pkg.okapi_send_request_and_wait_for_result import okapi_send_request_and_wait_for_result

Once this is done, you have to log-in into the platform, by receiving a JWT token from auth0:

okapi_login, error = okapi_init("OKAPI_URL", "YOUR_USERNAME","YOUR_PASSWORD")

The function returns a dict okapi_login, which mostly contains your JWT token, needed to get server access, and an error dict. The latter one contains three fields which give you an overview status as well as some further information. Make sure to _always_ check against the error['status']to catch your code in case something went wrong. It can contain the values FATAL, WARNING, INFO and NONE. In case of fatal errors, you should never use the result that might have been delivered. If you get a warning, you should check the reason for that. In most cases, it is nothing of concern. But especially if you get a warning together with an error[‘web_response’] of 202, it means that your process has been accepted, but is not fully processed yet. In that case, you should ask for the results short later again! Infos might be interesting to read, but do not indicate that something went wrong. If you get none, it means that no message was returned. error['message']gives you some extra information on the error that occurred, error['web_status']returns the http status code from the last request. Knowing this one is very helpful, in case there are issues with the internet connectivity, authentication or our server. Here is one example how to check the error:

if (error.get('status','') == 'FATAL'):
    print(error)
    exit('Error.')

Once you have received your token, you are ready to run computations. To send a request, you have to prepare a json object containing the description of your request. In python, you can use dicts for that, which are formatted identically to json. A detailed description of the available endpoints and the datatypes you can send is given in the API-Documentation. If that is set up, you can run a computation as follows

result, error = okapi_send_request_and_wait_for_result(okapi_login, request_body, url_endpoint_requests, url_endpoint_results, max_poll_time)

You see that you have to provide the okapi_login, the request_body, which contains your request as dict, the endpoint_url_request and the endpoint_url_results, which are given in the API-Documentation for all functionalities available, as well as the max_poll_time. The latter determines how long you maximum want to wait for the result (in seconds).

The result contains the result of your computation. If your result could not been processed in the allowed time, you will receive an error.

You probably noticed that this approach has one downside: You are blocking your code while something is running on an external machine. In many cases, you would not want that behaviour. For this, the connector provides different layers of abstraction: You can send a computation request and wait for results (what we did here), you can send a computation request and at a later point call a routine that waits for and gets the results, or you can handly both steps yourself.

In the example code below, you find simple implementations for all three cases.

Running the first calculation

For an easy start, you find a python script called tryout.py on Github, noted above. Make sure that you import the routines correctly, if you use that. Furthermore, make sure that you entered your username and password in the call of the authentication routine. If you just need one first example, you can also use the following python script. It calculates the pass of a satellite over a groundstation.

#!/usr/bin/python

import time

# Import OKAPI routines. If you use the script with OKAPI installed by PIP,
# adapt it (see below)
from okapi_init import okapi_init
from okapi_send_request import okapi_send_request
from okapi_get_result import okapi_get_result
from okapi_wait_and_get_result import okapi_wait_and_get_result
from okapi_send_request_and_wait_for_result import okapi_send_request_and_wait_for_result
from okapi_add_object import okapi_add_object
from okapi_change_object import okapi_change_object
from okapi_delete_object import okapi_delete_object
from okapi_get_objects import okapi_get_objects

# when using OKAPI installed with PIP:
# from okapi_pkg.okapi_init import okapi_init
# from okapi_pkg.okapi_send_request import okapi_send_request
# from okapi_pkg.okapi_get_result import okapi_get_result
# from okapi_pkg.okapi_wait_and_get_result import okapi_wait_and_get_result
# from okapi_pkg.okapi_send_request_and_wait_for_result import okapi_send_request_and_wait_for_result
# from okapi_pkg.okapi_add_object import okapi_add_object
# from okapi_pkg.okapi_change_object import okapi_change_object
# from okapi_pkg.okapi_delete_object import okapi_delete_object
# from okapi_pkg.okapi_get_objects import okapi_get_objects

#
# Init --> Get a token to run the analyses
#
# For auth info: See www.okapiorbits.space or contact us. Standard url is: https://platform.okapiorbits.com/api/
okapi_login, error = okapi_init(  < adress to okapi server as string > ,
                                 < user account as string > ,
                                 < user password as string > )

# check for the error status
if (error.get('status','') == 'FATAL'):
    print(error)
    exit('Error during authentification.')
# print(okapi_login)

#
# Pass predictions
#

#
# # Prepare your request
pass_pred_request_body = {
    "orbit":{
      "type": "tle.txt",
      "content": "1 25544U 98067A   18218.76369510  .00001449  00000-0  29472-4 0  9993\n2 25544  51.6423 126.6422 0005481  33.3092  62.9075 15.53806849126382"
    },
    "ground_location": {
      "type": "ground_loc.json",
      "content": {
        "altitude": 0.17012,
        "longitude": 10.07,
        "latitude": 50.2
      }
    },
    "time_window": {
      "type": "tw.json",
      "content": {
        "start": "2018-08-07T18:00:00.000Z",
        "end": "2018-08-08T00:00:00.000Z"
      }
    }
}

#
# # send different pass prediction pass prediction requests, use the bare functions to send and get results
#
# # send a request to use SGP4 for pass prediction
request_sgp4, error = okapi_send_request(okapi_login, pass_pred_request_body,
                                         'predict-passes/sgp4/requests')
if (error.get('status','') == 'FATAL'):
    print(error)
    exit()

# loop until the result has been fully processed. Alternatively, you could
# also just "sleep" for a while
counter = 0
while [1]counter < 15) and (error.get('web_status','') == 202:

  # get the result from SGP4
  result_sgp4, error = okapi_get_result(okapi_login, request_sgp4,
                                        'predict-passes/sgp4/results/{}/simple')

  if (error.get('status','') == 'FATAL'):
      print(error)
      exit()
  elif(error.get('status','') == 'WARNING'):
      print(error)

  counter = counter + 1

# print(result_sgp4)


#
# # First alternative: Send the result yourself, but use a dedicated function to wait for and get the result
#
# # send a request to use SGP4 for pass prediction
request_sgp4, error = okapi_send_request(okapi_login, pass_pred_request_body,
                                         'predict-passes/sgp4/requests')
if (error.get('status','') == 'FATAL'):
    print(error)
    exit()

# call the function to wait for and get the result
result_sgp4, error = okapi_wait_and_get_result(okapi_login, request_sgp4,
                                      'predict-passes/sgp4/results/{}/simple', 15)

if (error.get('status','') == 'FATAL'):
    print(error)
    exit()
elif(error.get('status','') == 'WARNING'):
    print(error)

# print(result_sgp4)

#
# # Third alternative: Use a function to send, wait-for and get the result. Note that this might block your code while running
#
# # send a request to use SGP4 for pass prediction
result_sgp4, error = okapi_send_request_and_wait_for_result(okapi_login, pass_pred_request_body,
                                      'predict-passes/sgp4/requests',
                                      'predict-passes/sgp4/results/{}/simple', 15)

if (error.get('status','') == 'FATAL'):
    print(error)
    exit()
elif(error.get('status','') == 'WARNING'):
    print(error)

References

References
1 counter < 15) and (error.get('web_status','') == 202
Weiter Java
Inhaltsverzeichnis