How to use Axios/Vue.js to call data from SQLite/Django backend?

て烟熏妆下的殇ゞ 提交于 2020-01-06 08:11:31

问题


Status Quo:

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.

Conclusion: I have one API call per website visitor.

Desired status:

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.

Questions:

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.) 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.) 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.) 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: (as of now directly fetching the 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);
      });
    }
});

In advance thank you very much for your help!


回答1:


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)

For more details visit django's documentation

Better would be if you use DRF for making rest apis. It's much easier.



来源:https://stackoverflow.com/questions/58790507/how-to-use-axios-vue-js-to-call-data-from-sqlite-django-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!