簡體   English   中英

使用AJAX執行拍攝照片的python腳本(raspberry pi)

[英]Using AJAX to execute a python script that takes a picture (raspberry pi)

我正在一個項目中,我需要為其構建一個Web界面,以允許與Raspberry Pi相機進行交互。 我在后端使用Django和python。 我希望能夠在Web界面上按下一個按鈕,該按鈕將執行python腳本以使用pi相機拍照。 我以為我需要使用AJAX來完成此操作,但是我不太了解如何設置它。 我對Django本身比較陌生。

因此,假設您有一個Python函數,該函數使用相機拍攝照片並將路徑返回到文件。

from my_module import take_pic

my_pic = take_pic()
print(my_pic)  # '/path/to/the/picture'

您是說您不知道views.py應該是什么樣子,所以我假設您尚未准備好Django代碼。 要創建Django項目,請安裝Django並使用django-admin startproject NAME

因此,您需要的是Django視圖及其關聯的URL。 讓我們從URL開始:

# urls.py
from . import views

urlpatterns = [
    url(r'^take_pic/', views.take_picture, name='take_pic'),
]

現在,在urls.py所在的文件夾中創建views.py模塊。

# views.py
from django.http import JsonResponse

from my_module import take_pic


def take_picture(request):
    my_pic = take_pic()
    return JsonResponse({'path': my_pic})

最后,在您的Javascript代碼中(最有可能是在Django HTML模板中,用另一個視圖呈現,但我將其保留為練習):

// this example uses JQuery, but you can find plain Javascript examples on the net

<button id="my-button"></button>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>

  $(document).ready(function () {

    $('my-button').click(function() {

      // url name here is what you wrote in urls.py
      $.getJSON('{% url "take_pic" %}', function (data) {

        var picture_path = data.path;
        // add an HTML <img> tag where you need it, using the picture path
        // note that your view might need to return a relative path, not absolute
      });

    });

  });

</script>

我認為這是一個不錯的起點!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM