我有创建 SqLite 数据库的桌面应用程序。
我想使用该数据在本地静态网页上制作报告。 但是,我不确定如何连接到现有数据库 - 我知道这存在安全问题。
这可以用 JavaScript 实现吗?我该怎么做?
最佳答案
一种选择是像这样从模板传递数据:
def index(request):
# Calculate your precious data here, for example using the django.core.serializers class:
data = serializers.serialize('json', FooModel.objects.all())
return render(request, 'templates/index.html', {'data': data})
然后在您的 templates/index.html
中,您可以执行如下操作:
<script>
window.data = {{data|default:"{}"|safe}};
</script>
查看 safe filter .
通过这种方式,您可以通过初始请求获取从后端到前端的所有数据,而无需创建任何其他请求,也无需使用 JS 直接与您的数据库通信。
另一种选择是使用fetch
:
您可以创建一个 View (您可以使用 Django REST 框架,但这取决于您尝试使用它的目的,无论如何主要思想保持不变):
from django.http import HttpResponseNotAllowed, JsonResponse
from django.core import serializers
from .models import FooModel # for example
def myview(request):
if request.method != "POST":
return HttpResponseNotAllowed(['POST'], "Only POST is allowed to this URL.")
# Get your precious data, let's use the same example as before:
data = serializers.serialize('json', FooModel.objects.all())
return JsonResponse(data)
在你的 urls.py
中注册它:
urlpatterns = [
...
path('api/retrievepreciousdata', views.myview),
...
]
然后我们可以使用fetch
来获取它:
fetch("/api/retrievepreciousdata", {
method: "POST",
headers: {
//For CSRF protection:
//I use `js-cookie` to get the cookies, it's up to you really
"X-CSRFToken": Cookies.get("csrftoken"),
"X-Requested-With": "XMLHttpRequest",
},
}).then(response => {
if(!response.ok) {
console.log("Dang it, the response isn't OK... Response code is", response.status);
}
return response.json()
}).then(json => {
console.log("I did it! My precious data is:", json);
}).catch(e => {
console.log("Dang it, something went wrong while retrieving my precious data:", e);
});
关于javascript - 从现有的 sqlite 数据库中获取数据到网页中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51837009/