Search code examples
pythonbottle

How do I send python lists to a bottle server?


I have a python file which has 4 python lists that gets basic information (ip, host, mac, signal) from devices connected to a rpi hotspot. I would like to send those lists from the Rpi to a bottle server constantly because that information can change over time (device disconnects, changes its signal ...). And finally, print that information on an HTML. How can I constantly send information in a simple way? Websockets? Ajax?


Solution

  • you could setup a cron job on your RPI hotspot which periodically executes a curl command with the contents of the python lists as JSON. You mention "python lists" in your question, if you are just storing the data in a .py file then I would suggest writing it to another format like json instead.

    Send the data from RPI device every minute

    # 1 0 0 0 0 curl -vX POST http://example.com/api/v1/devices -d @devices.json --header "Content-Type: application/json"
    

    Then in your bottle file have a method that receives the data POST and another that can display the data GET. The example just writes the received data to a json file on the server

    from bottle import route, run
    import json
    
    @route('/api/v1/devices', method='GET')
    def index(name):
        with open('data.json') as f:  
            return json.load(f)
    
    
    @route('/api/v1/devices', method='POST')
    def index(name):
        req_data = request.json
        with open('data.json', 'r+') as f:
            data = json.load(f.read())
            # output = {**data, **req_data} # merge dicts
            output = data + req_data # merge lists
            f.seek(0)
            f.write(output)
            f.truncate()
        return {success: True}
    
    run(host='localhost', port=8080)
    

    Note: I didn't test this code it is to give you and idea of how you might accomplish your request.