Search code examples
javapythontwisted

Every second web service call


I need to write a short script that can consume a REST call, every second. Most of the time, it will get back a response with:

"status": "idle"

However, if something is happening, we will instead get "status": "scan", with some additional parameters.

We consume those parameters, and then make a different call to a cloud service.

We would then get a response from that, and send back the JSON to the local web service.

Then once completed, it should go back to checking every second for a status other than idle.

  1. Is Python a good language to do this on, or should be be using Java?
  2. The every second call is over a LAN, not concerns over latency or internet bandwidth.
  3. If it crashes or gets an exception we need to be able to restart easily.

Any pointers on this would be most appreciated.

The response coming back is in the format:

[{'status': 'idle', 'log_updated_at': None, 'eprom_version': '03.21', 'data': {}, 'controller_type': 'single_ball', 'address': 1}]

I am having some challenges getting that understood as json, to have the status element be accessed by the logic below.


Solution

  • import time
    import requests
    
    while True:
        try:
            r = requests.get(local_rest_url)
            json_data = r.json()
    
            if json_data.get('status') == 'idle':
                time.sleep(1)  # wait 1 second
                continue       # and try again
    
            r = requests.post(cloud_service_url, data=json_data)
            cloud_response = r.json()
    
            r = requests.post(local_rest_url, data=cloud_response)
        except Exception:
            pass  # any error, just ignore and restart the loop