Django:从开源中获取数据 API
Django: Fetching data from an open source API
我正在尝试从 https://date.nager.at/ with the documentation at https://date.nager.at/swagger/index.html 获取 F运行ce、澳大利亚和德国的 public 假期数据,并将其存储在 JSON 文件中。
到现在为止,我已经创建了一个端点 /fetch_and_save,它有自己的 URL,但只能在 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 应用程序。
这里有一些线索,如何以简单的方式做到这一点:
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
,您将获取德国的 public 假期 2020 并将其保存到名称为 public_holidays_DE_2020.json
的 json 文件中。
我正在尝试从 https://date.nager.at/ with the documentation at https://date.nager.at/swagger/index.html 获取 F运行ce、澳大利亚和德国的 public 假期数据,并将其存储在 JSON 文件中。
到现在为止,我已经创建了一个端点 /fetch_and_save,它有自己的 URL,但只能在 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 应用程序。
这里有一些线索,如何以简单的方式做到这一点:
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
,您将获取德国的 public 假期 2020 并将其保存到名称为 public_holidays_DE_2020.json
的 json 文件中。