假设你有一个 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>
我认为这是一个很好的起点!