'PUT and POST only specific fields without getting Serializer error in django
Here i wanted to post my data from thingspeak server to Django models and I have imported them by calling functions from DjangoApp.Thingspeak file.But, in this code GET and DELETE method works perfectly but, POST and PUT generates an error exception however, it also take some time for POST and PUT method too. But, as soon as I re-run my server. It catches value Immediately. Can anybody help me to debug this...
Here is my code for views.py
import json
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from DjangoApp.serializers import PatientSerializer
from DjangoApp.models import Patient
from DjangoApp.Thingspeak import tempValue,humValue,bodyTempValue
# Create your views here.
@csrf_exempt
def PatientAPI(request,id=0):
if request.method == 'GET':
patients = Patient.objects.all()
patients_serializer = PatientSerializer(patients,many=True)
return JsonResponse(patients_serializer.data,safe=False)
elif request.method == 'POST':
patient_data = JSONParser().parse(request)
patient = Patient.objects.create(PatientId=patient_data['PatientId'],PatientName=patient_data['PatientName'],RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue())
patient_data = json.parse(patient)
patients_serializer = PatientSerializer(data=patient_data)
if patients_serializer.is_valid():
patients_serializer.save()
return JsonResponse("Added Successfully", safe=False)
return JsonResponse("Failed to add", safe=False)
elif request.method == 'PUT':
patient_data = JSONParser().parse(request)
if patients_Serializer.is_valid():
patient=Patient.objects.filter(PatientId=patient_data['PatientId']).update(RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue())
patient = json.parse(patient)
patients_Serializer = PatientSerializer(patient, data=patient_data)
return JsonResponse("Updated Successfully", safe=False)
return JsonResponse("Failed to Update")
elif request.method == 'DELETE':
patient = Patient.objects.get(PatientId=id)
patient.delete()
return JsonResponse("Deleted Successfully", safe=False)
and Thingspeak.py code
import re
import urllib.request
with urllib.request.urlopen("https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true") as url:
s = repr(url.read())
def tempValue():
temp = re.search('field1":"(.+?)",',s)
if temp:
return(temp.group(1))
def humValue():
hum = re.search('field2":"(.+?)",',s)
if hum:
return(hum.group(1))
def bodyTempValue():
bodyTemp = re.search('field3":"(.+?)",',s)
if bodyTemp:
return(bodyTemp.group(1))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
