Flask Button run Python without refreshing page?

前端 未结 3 456
攒了一身酷
攒了一身酷 2020-12-31 16:42

I am just getting started into python and flask (for the raspberry pi). I want a web application that would execute some python code to pan and tilt a camera and display a v

3条回答
  •  情书的邮戳
    2020-12-31 17:29

    I would split it out into two routes to make it easier to see what you have to do:

    LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"
    AVAILABLE_COMMANDS = {
        'Left': LEFT,
        'Right': RIGHT,
        'Up': UP,
        'Down': DOWN,
        'Reset': RESET
    }
    
    @app.route('/')
    def execute():
        return render_template('main.html', commands=AVAILABLE_COMMANDS)
    
    @app.route('/')
    def command(cmd=None):
        if cmd == RESET:
           camera_command = "X"
           response = "Resetting ..."
        else:
            camera_command = cmd[0].upper()
            response = "Moving {}".format(cmd.capitalize())
    
        # ser.write(camera_command)
        return response, 200, {'Content-Type': 'text/plain'}
    

    Then in your template you just need to use some JavaScript to send off the request:

    {# in main.html #}
    {% for label, command in commands.items() %}
        
    {% endfor %}
    
    {# and then elsewhere #}
    
    

提交回复
热议问题