首页 > 解决方案 > 从现有的 sqlite DB 中获取数据到网页中

问题描述

我有创建 SqlLite DB 的桌面应用程序。

我想使用这些数据在本地静态网页上制作报告。但是我不确定如何连接到现有数据库 - 我知道这存在安全问题。

这对 JavaScript 可行吗?我该怎么做呢?

标签: javascriptsqliteweb-services

解决方案


一种选择是从模板中传递数据,如下所示:

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>

检查安全过滤器

这样,您可以通过初始请求从后端到前端获取所有数据,而无需创建任何其他请求,或直接使用 JS 与您的数据库通信。


另一种选择是使用fetch

您可以创建一个视图(您可以使用 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);
});

推荐阅读