PUT和POST仅针对特定字段,而没有在django中获得Serializer错误



这里我想把我的数据从thingspeak服务器发布到Django模型,我已经通过调用DjangApp.thingspeak文件中的函数导入了它们。但是,在这段代码中,GET和DELETE方法工作得很好,但是POST和PUT生成了一个错误异常,POST和PUT方法也需要一些时间。但是,只要我重新运行服务器。它立即抓住价值。有人能帮我调试一下吗。。。

这是我的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)

和Thingspeak.py代码

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

请不要用正则表达式解析JSON:JSON是一种递归语言,无法用正则表达式(正确(解析,因为JSON不是正则语言

但是,即使您只解析可能是常规语言的正则表达式的子部分,该语言也比最初看起来要复杂得多:有关于转义字符串的规则等。因此,即使您设法通过正则表达式捕获数据,正确处理它也会很复杂。

您可以将其解释为JSON对象,然后访问与密钥相关联的值:

importrequests
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']

相关内容

最新更新