python - 如何使用 Django/Python 在 SQLite 中存储获取的 JSON 数据

标签 python json django sqlite

这是我第一次尝试使用 Django Models,我不断地迈出小步,但暂时陷入困境。

我想使用 Python/Django 将从第三方 API 获取的数据存储到我的 SQLite 数据库中(我在 Django 上构建我的 Web 应用程序)。

理论上我的想法是这样的:

  • 使用 request 获取数据图书馆。
  • 对其进行操作使其符合 Python
  • 通过将数据分配给变量来提取数据
  • 使用 Django 将数据推送到 SQLite DB model
  • 获取 SQLite 数据以渲染前端

现在,这就是我到目前为止所拥有的:

Quotes_app/models.py:

from django.db import models

# create class to store API fetched data

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

当我运行models.py时我收到以下错误:

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
[Finished in 0.513s]

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=XXX&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']

rates_new = ratesEUR(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)

当我运行views.py时我收到以下错误,并且数据库未填充:

from Quotes_app.models import ratesEUR
ModuleNotFoundError: No module named 'Quotes_app'
[Finished in 0.421s]

json 响应如下所示:

{
    "success": true,
    "timestamp": 1573382946,
    "base": "EUR",
    "date": "2019-11-10",
    "rates": {
        "AED": 4.047045,
        "AFN": 86.223727,
        "ALL": 123.086065,
        "AMD": 525.791674,
        [...]
}

Settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Quotes_app',
    'Wiki_app',
]

除了上述错误之外,我还有以下问题:

  1. 我是否正确定义了表/模型以便能够相应地表示 JSON 数据,或者我是否需要某种嵌套结构,甚至是链接到另一个表的附加表?

  2. 是否可以选择每 120 秒自动发出一次请求?

  3. 如何用数据库中新获取的数据覆盖最后一个数据对象? (我不再需要过时的数据了)

  4. 在 module.py 文件中发出请求是常见的还是以其他方式发出请求?

预先感谢您非常的建议!

最佳答案

首先,您需要激活环境,然后运行 ​​Django 项目。

  1. 我是否正确定义了表/模型以便能够相应地表示 JSON 数据,或者我是否需要某种嵌套结构,甚至是链接到另一个表的附加表?

    Ans: - 不,您应该在模型类中采用正确的数据类型来存储数据。

class ratesEUR(models.Model):
    timestamp = models.DateTimeField(auto_now_add=False) # the timestamp data should be in the datetime format, you should convert your timestamp to datetime format and store it into the database

    base = models.CharField(max_length=3)
    date = models.DateField(auto_now=False, auto_now_add=False) # your json date is in string format so you have to convert it into data time format

    rates = JSONField() # your json have rates value as json, so need to store it in json field

    def __str__(self):
        return self.base # this function should return string type data value only
  • 是否可以选择每 120 秒自动发出一次请求?

    Ans:- 是的,你可以使用 celery 包。

  • 如何用数据库中新获取的数据覆盖最后一个数据对象? (我不再需要过时的数据)。

    Ans:- ratesEUR.objects.filter(id=id).update(timestamp=timestamp, base=base, date=date, rates=rates)

  • 在 module.py 文件中发出请求是否常见?或者有不同的建议方法吗?

    Ans:- 不,最好将功能编写在views.py模块中。

  • 关于python - 如何使用 Django/Python 在 SQLite 中存储获取的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58789237/

    相关文章:

    python - 为什么 numpy 不允许分配双重索引的 numpy 数组?

    python - Model.save() 和 ModelForm.save() 一起工作

    java - 过滤 Json 以仅显示用户想要的结果

    python - django - 如何在模板中插入上传文件的内容?

    Django reportlab 插入分页符 html 端

    python - 可以同时安装 Python 2.7 和 3.5 吗?

    python - 用编译的 Julia 打包 Python?

    python - BashOperator 为其他 PythonOperators 中使用的库引发 ImportError

    json - 使用python将json和文件发送到flask

    python - 如何将 networkx (python) 节点序列化为 json 格式?