我正在嘗試使用 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)
]
而已。這只是一個你好世界的應用程式。
uj5u.com熱心網友回復:
在這里你有一些線索,如何以簡單的方式做到這一點:
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)
]
然后,如果您添加 ie /2020/DE,您將獲取德國 2020 年公共假期并將其保存到名稱為 .json 的 json 檔案中public_holidays_DE_2020.json。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/416262.html
標籤:
