【问题标题】:Django: Fetching data from an open source APIDjango:从开源 API 获取数据
【发布时间】:2022-01-19 06:56:35
【问题描述】:

我正在尝试使用https://date.nager.at/swagger/index.html 的文档从https://date.nager.at/ 获取法国、澳大利亚和德国的公共假期数据,并将其存储在 JSON 文件中。

到目前为止,我已经使用自己的 URL 创建了一个端点 /fetch_and_save,但只能在 views.py 文件中写入虚拟数据。如何获取上面的数据并通过 Django 将其存储在数据库中?

编辑:我被要求显示代码。 我跑了

python3 manage.py startapp fetch_and_save

创建抓取应用程序,我在 storefront/urls.py 中有以下 URL 模式:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('fetch_and_save/', include('fetch_and_save.urls')),
]

然后我在 fetch_and_save/views.py 中添加了函数:

def say_hello(request):
    return HttpResponse('Fetch the data from date.nager.at here')

我在 fetch_and_save/urls.py 中调用它:

urlpatterns = [
    path('', views.say_hello)
]

就是这样。它只是一个 hello world 应用程序。

【问题讨论】:

  • 请向我们展示您的代码 :)

标签: json django database fetch-api


【解决方案1】:

这里有一些线索,如何以简单的方式做到这一点:

fetch_and_save/views.py

import json
import requests


def get_public_holidays(request, year, tag):
    response = requests.get(f'https://date.nager.at/api/v2/PublicHolidays/{year}/{tag}')
    with open(f'public_holidays_{tag}_{year}.json', 'w') as outfile:
        json.dump(response.text, outfile)
    ...

fetch_and_save/urls.py

urlpatterns = [
    path('<int:year>/<str:tag>/', views.get_public_holidays)
]

然后,如果您添加即/2020/DE,您将获取德国 2020 年的公共假期并将其保存到名称为 public_holidays_DE_2020.json 的 json 文件中。

【讨论】:

    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2017-10-30
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    相关资源
    最近更新 更多