Home > Mobile >  PUT and POST only specific fields without getting Serializer error in django
PUT and POST only specific fields without getting Serializer error in django

Time:02-11

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))   
 

CodePudding user response:

Please do not parse JSON with regexes: JSON is a recursive language which can not be parsed (correctly) with a regular expression since JSON is not a regular language.

But even if you only parse subparts of regexes that might be a regular language, the language is a lot more complicated than what it looks like at first: there are rules about escaping strings, etc. so even if you manage to capture the data through a regex, it would be complicated to process it correctly.

You can interpret it as a JSON object, and then access the values associated with a key:

import requests

url = 'https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true'

response = requests.get(url).json()
temp_value = response['field1']
hum_value = response['field2']
body_temp_value = response['field3']
  • Related