如何使用Axios/Vue.js从SQLite/Django后端调用数据? [英] How to use Axios/Vue.js to call data from SQLite/Django backend?

查看:451
本文介绍了如何使用Axios/Vue.js从SQLite/Django后端调用数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现状:

每当用户访问我的Web应用程序时,Axios都会请求第三方API来获取数据并使用v-for使用该数据填充前端.

Whenever a user visits my web application, Axios makes a request to a third party API to fetch data and populate the frontend with that data using v-for.

结论:每个网站访问者都有一个API调用.

Conclusion: I have one API call per website visitor.

期望的状态:

每当用户访问我的Web应用程序时,Axios均应从SQLite数据库中获取数据,该数据库本身每隔XX秒由python request填充一次,以减少API调用.

Whenever a user visits my web application, Axios shall fetch the data from the SQLite database which itself is populated every XX seconds by a python request to reduce API calls.

问题:

现在,我使用Django modelsviews实现了SQLite数据库.到目前为止,该API会定期获取并正确更新数据库表.

Now I implemented a SQLite database using Django models and views. So far so good, the API gets fetched regularly and updates the database table properly.

1.)现在如何使用Axios调用数据库中的数据?根据我的研究,Axios某种程度上需要调用view,而view将从数据库中调用数据,这是正确的吗?

1.) How can I now call the data in the database using Axios? As by my research Axios somehow needs to call a view and the view will call the data from the database, is this correct?

2.).如果Axios需要调用view,我是否需要另一个view.py文件来调用数据库?如果我将所需的view函数插入到现有的view.py文件中,它将启动另一个API调用,不是吗?

2.) If Axios needs to call a view, do I need another view.py file that calls the database? If I would insert the needed view function into the existing view.py file it would initiate another API call, wouldn't it?

3.),如何实现指向Axios的view函数的链接?代替第三方API URL,我会使用view文件的路径吗?

3.) And how can I implement the link to the view function to Axios? Instead of a third party API url would I just use the path to the view file?

Quotes_app/Views.py:

from django.shortcuts import render
from Quotes_app.models import ratesEUR

import json
import requests

response = requests.get("http://data.fixer.io/api/latest?access_key=XXXX&base=EUR")

rates_EUR = json.loads(response.content.decode('utf-8'))
timestamp = rates_EUR['timestamp']
base = rates_EUR['base']
date = rates_EUR['date']
rates = rates_EUR['rates']
id = 1

rates_new = ratesEUR(id=id, timestamp=timestamp, base=base, date=date, rates=rates)
rates_new.save()


def render_Quotes_app(request, template="Quotes_app/templates/Quotes_app/Quotes_app.html"):
    return render(request, template)

Quotes_app/models.py:

from django.db import models


class ratesEUR(models.Model):
    timestamp = models.CharField(max_length=10)
    base = models.CharField(max_length=3)
    date = models.DateField(auto_now=False, auto_now_add=False)
    rates = models.CharField(max_length=8)

    def __str__(self):
        return self.base

Vue.js/axios :(从现在开始直接获取API)

Vue.config.devtools = true;

var app = new Vue({
  delimiters: ['[[', ']]'],
  el: '.eurQuotesWrapper',
  data() {
    return {
      rates: [],
    };
  },
  computed: {
    rates1() {
      const ratesArr1 = Object.entries(this.rates);
      const ret = ratesArr1.reduce((a, c, i, d) => {
        if (i < d.length / 2) a[c[0]] = c[1];
        return a;
      }, {});
      console.log('rates1', ret);
      return ret;
    },
    rates2() {
      const ratesArr2 = Object.entries(this.rates);
      const ret = ratesArr2.reduce((a, c, i, d) => {
        if (i >= d.length / 2) a[c[0]] = c[1];
        return a;
      }, {});
      console.log('rates2', ret);
      return ret;
    }
  },
  created() {
    axios
      .get("http://data.fixer.io/api/latest?access_key=XXXX&base=EUR")
      .then(response => {
        this.rates = response.data.rates;
        console.log(this.rates);
        for(key in this.rates) {
          this.rates[key] = new Intl.NumberFormat('de-DE', {
            minimumFractionDigits: 5,
            maximumFractionDigits: 5
          }).format(this.rates[key]);
        }
        console.log(this.rates);
      });
    }
});

在此先非常感谢您的帮助!

推荐答案

您可以使用DRF(Django Rest Framework)制作REST API ,也可以使用JsonResponse 发送JSON对象作为响应.

You can use DRF(Django Rest Framework) to make REST API's or You can use JsonResponse to send JSON objects as response.

from django.http import JsonResponse



data = # Your data
JsonResponse(data, encoder=MyJSONEncoder)

有关详细信息,请访问django的文档

这篇关于如何使用Axios/Vue.js从SQLite/Django后端调用数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆