2014-02-05 4 views
5

Я только начинаю в питон и колбу (для малины пи). Я хочу, чтобы веб-приложение выполняло некоторый код python для панорамирования и наклона камеры и отображения видеопотока.Flask Button запускает Python без обновления страницы?

Моего код uptil теперь для колбы:

from flask import Flask, render_template 
import time 
import serial 
#ser = serial.Serial('/dev/ttyUSB0',9600) 
app = Flask(__name__) 
@app.route('/') 
@app.route('/<cmd>') #each button in my html redirects to a specified directory 
def execute(cmd=None): 
if cmd == "down": 
    print "Moving Down" 
    #ser.write("D") 

if cmd == "up": 
    print "Moving Up" 
    #ser.write("U") 

if cmd == "left": 
    print "Moving Left" 
    # ser.write("L") 

if cmd == "right": 
    print "Moving Right" 
    #ser.write("R") 

if cmd == "reset": 
    print "Reseting.." 
    #ser.write("X") 
return render_template("main.html") 


if __name__ == "__main__": 
app.run(host='0.0.0.0', port=8080, debug=True) 

Проблема мой код relys на каждую кнопку переадресации на новый directry, в то время как это работает хорошо, он обновляет страницу каждый раз, что означает мой снова добавили видео перезагрузки и буферы. Есть ли лучший способ обнаружения нажатия кнопки, а затем выполнения кода python с использованием фляжки?

+2

Для этого вам нужно использовать AJAX звонки с JavaScript работает на этой странице. –

ответ

7

Я бы разделить его на два маршрута, чтобы сделать его легче увидеть, что вы должны сделать:

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('/<cmd>') 
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'} 

Затем в шаблоне вам просто нужно отправлять запрос использовать некоторые JavaScript:

{# in main.html #} 
{% for label, command in commands.items() %} 
    <button class="command command-{{ command }}" value="{{ command }}"> 
     {{ label }} 
    </button> 
{% endfor %} 

{# and then elsewhere #} 
<script> 
// Only run what comes next *after* the page has loaded 
addEventListener("DOMContentLoaded", function() { 
    // Grab all of the elements with a class of command 
    // (which all of the buttons we just created have) 
    var commandButtons = document.querySelectorAll(".command"); 
    for (var i=0, l=commandButtons.length; i<l; i++) { 
    var button = commandButtons[i]; 
    // For each button, listen for the "click" event 
    button.addEventListener("click", function(e) { 
     // When a click happens, stop the button 
     // from submitting our form (if we have one) 
     e.preventDefault(); 

     var clickedButton = e.target; 
     var command = clickedButton.value; 

     // Now we need to send the data to our server 
     // without reloading the page - this is the domain of 
     // AJAX (Asynchronous JavaScript And XML) 
     // We will create a new request object 
     // and set up a handler for the response 
     var request = new XMLHttpRequest(); 
     request.onload = function() { 
      // We could do more interesting things with the response 
      // or, we could ignore it entirely 
      alert(request.responseText); 
     }; 
     // We point the request at the appropriate command 
     request.open("GET", "/" + command, true); 
     // and then we send it off 
     request.send(); 
    }); 
    } 
}, true); 
</script> 
+0

Привет, благодарю за ваш ответ, но поскольку я новичок в javascript, я действительно не понимаю, как это работает, и я не получаю это от работы:/вы могли бы показать мне, как справляться с одним нажатием одной кнопки самым простым способом, который будет печатать «X» на python? я бы изучил это подробно. –

+0

@ user3264137 - какие ошибки отображаются в консоли отладки вашего браузера при загрузке страницы? (Я предполагаю, что *, что * - это то, что ломается, а не внутренний код). –

+0

Я пробовал это, но теперь, когда я нажимаю «Отправить», вместо перехода на новую страницу я получаю «Клиент отключен». – Aspen

0

у меня такая же проблема, и ответ прост с помощью Ajax XmlHttpRequest:

// send a request, but don't refresh page 
xhttp = new XMLHttpRequest(); 
xhttp.open("GET", "your script action", true); 
xhttp.send(); 

Вот небольшой пример, назвав текущий сценарий с параметрами «как», встроенных в функции:

function likeStuffs() 
{ 
    // send a request, but don't refresh page 
    xhttp = new XMLHttpRequest(); 
    xhttp.open("GET", "?like", true); 
    xhttp.send(); 
} 
Смежные вопросы