How to save data from API whenever it updates (django)
there is an API that comes from a device. This device updates its sampling variables every 2 minutes , maybe the results change or may not(because of some conditions). i want to store this API exactly whenever the device updates itself.
i have tried using background tasks with 2 minutes intervals but for example the latest result doesn't match the API at the moment , because of the delay which is convincing. I am just curious to know if is it possible to store the data as soon as the device updates itself?
Create a view in the app to handle the request for the API data. In the view, you can make a request to the API and save the data to the model. For example:
from django.shortcuts import render
import requests
def save_api_data(request):
# Make a request to the API
response = requests.get('http://api.example.com/data')
data = response.json()
# Save the data to the model
device_data = DeviceData.objects.create(
device_id=data['device_id'],
variable1=data['variable1'],
variable2=data['variable2']
)
device_data.save()
return render(request, 'api_data/data_saved.html')
To save the data from the API whenever it updates, you can set up a scheduled task to make a request to the API and save the data to the model at regular intervals. One way to do this is to use the django-scheduler
package, which allows you to define scheduled tasks in Django using the @periodic_task
decorator.
Then, in the tasks.py
file of the app, define a periodic task to make the request to the API and save the data. For example:
from django_celery_beat.models import PeriodicTask, IntervalSchedule
from django.utils import timezone
@periodic_task(run_every=(IntervalSchedule(minutes=2)))
def save_api_data():
# Make a request to the API
response = requests.get('http://api.example.com/data')
data = response.json()
# Save the data to the model
device_data = DeviceData.objects.create(
device_id=data)
I hope it can help. Incase of mistake, I hope someone can correct it.