[英]Using AJAX to execute a python script that takes a picture (raspberry pi)
I am working on a project for which I need to build a web interface that will allow interaction with a Raspberry Pi camera. 我正在一个项目中,我需要为其构建一个Web界面,以允许与Raspberry Pi相机进行交互。 I am using Django and python for the back end. 我在后端使用Django和python。 I want to be able to press a button on the web interface that will execute a python script to take a picture with the pi camera. 我希望能够在Web界面上按下一个按钮,该按钮将执行python脚本以使用pi相机拍照。 I am thinking I need to use AJAX to complete this, but I don't really understand how I would set this up. 我以为我需要使用AJAX来完成此操作,但是我不太了解如何设置它。 I am relatively new to Django itself. 我对Django本身比较陌生。
So let's assume you have a Python function that takes a picture with the camera and returns the path to the file. 因此,假设您有一个Python函数,该函数使用相机拍摄照片并将路径返回到文件。
from my_module import take_pic
my_pic = take_pic()
print(my_pic) # '/path/to/the/picture'
You're saying you don't know what the views.py
should look like so I'll assume that you don't have any Django code ready. 您是说您不知道views.py
应该是什么样子,所以我假设您尚未准备好Django代码。 To create a Django project, install Django and use django-admin startproject NAME
. 要创建Django项目,请安装Django并使用django-admin startproject NAME
。
So what you need is a Django view and it's associated URL. 因此,您需要的是Django视图及其关联的URL。 Let's begin with the URL: 让我们从URL开始:
# urls.py
from . import views
urlpatterns = [
url(r'^take_pic/', views.take_picture, name='take_pic'),
]
Now, create the views.py
module in the same folder that urls.py
is in. 现在,在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})
Finally in your Javascript code (most probably in an Django HTML template, rendered with another view, but I'll leave that as an exercise): 最后,在您的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>
I think this is a good place to start! 我认为这是一个不错的起点!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.