def XMLDataCreate(request): """ Request XML data and save to database """ if request.method == 'POST': data = request.data if data: if 'devices' in data and data['devices']: # save the devices information for device_code,device_name in data['devices'].items(): device, created = Device.objects.get_or_create(code=device_code, name=device_name) if 'data' in data: for element in data['data']: if 'device' in element and 'value' in element : element_data={ 'device':element['device'], 'value':element['value'], 'record_time':datetime.datetime.fromtimestamp(data['record_time']), 'data_id':data['id'], } serializer = ElementSerializer(data=element_data) if serializer.is_valid(): serializer.save() """ May use apscheduler to handle mass data """ #scheduler.add_job(serializer.save(),) else: response(serializer.errors,status=status.HTTP_424_FAILED_DEPENDENCY) return response(status=status.HTTP_201_CREATED) return response(status=status.HTTP_400_BAD_REQUEST)
def echo(request): """ Request json data and return it """ if request.method == 'POST': data = request.data if data: return response(data, status=200, content_type=request.content_type) return response(status=status.HTTP_400_BAD_REQUEST)
def display(request, id): """ Response json data """ try: record = Record.objects.get(pk=id) serializer = DataSerializer(record.data_set.all(), many=True) return response(serializer.data, status=200) except Record.DoesNotExist: return response(status=status.HTTP_404_NOT_FOUND)
def echo(request, format=None): if request.method == 'GET': meizis = Meizis.objects.all() serializer = MeiziSerializer(meizis, many=True) return response(serializer.data) elif request.method == 'POST': serializer = MeiziSerializer(data=request.data) if serializer.is_valid(): serializer.save() return response(serializer.data, status=status.HTTP_201_CREATED) return response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def echo(request): """ Request json data and return it """ if request.method == 'POST': #serialize = DeviceTypeSerializer( DeviceType.objects.get(unit='V') ) dtset = DeviceType.objects.all() serialize = DeviceTypeSerializer(dtset, many=True) if serialize: input_record = hedersgavaxml.XMLParser.parse(request.body) return response(json.dumps(input_record), status=200, content_type='application/json') return response(status=status.HTTP_400_BAD_REQUEST) return None
def XMLDataList(request): """ API to let client fetch the reformatted data by time """ if request.method == 'GET': serializer = ElementSerializer(Element.objects.all().order_by('record_time'), many=True) return JsonResponse(serializer.data,json_dumps_params={'indent': 2}, safe=False) return response(status=status.HTTP_400_BAD_REQUEST)
def receive(request): """ Request xml data and response json """ data = request.data serializer = RecordSerializer(data=data) if serializer.is_valid(raise_exception=True): record = serializer.save() data_serializer = DataSerializer(record.data_set.all(), many=True) return response(data_serializer.data, status=200)
def echo_filter(request, filter_timestamp): #Request json data and return it """ echo views : converting timestamp as url parameter to datetime #TODO: exception handling for dtset = DeviceRecords.objects.filter if objects not found """ if request.method == 'GET': #tzname = request.session.get('django_timezone') #local_tz = pytz.timezone(timezone.now()) local_tz = pytz.timezone('Asia/Jakarta') utc_dt = datetime.utcfromtimestamp(filter_timestamp).replace(tzinfo=pytz.utc) dt_value = local_tz.normalize(utc_dt.astimezone(local_tz)) dt_value = dt_value.strftime('%Y-%m-%dT%H:%M:%SZ') print(dt_value) dtset = DeviceRecords.objects.filter(record_time=dt_value)#.union() #dtset = DeviceRecords.objects.all() serialize = DeviceRecordsSerializer(dtset, many=True) if serialize: return response(serialize.data, status=200, content_type=request.content_type) return response(status=status.HTTP_400_BAD_REQUEST) return None
def get_detail_record(request, id): """ GET response in json. Client can fetch the data by date time with query params: /data/<id>/?date=YYYY-mmm-dd H:M:S """ if request.method == 'GET': data = id date = request.query_params.get('date') if date: queryset = DeviceRecord.objects.filter(record=data, created__startswith=date) serializer = DataSerializer(queryset, many=True) return response(serializer.data, status=200) else: queryset = DeviceRecord.objects.filter(record=data) serializer = DataSerializer(queryset, many=True) return response(serializer.data, status=200) return response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): serializer = IDSerializer(data=request.DATA) if serializer.is_valid(): bang = None try: bang = Bang.objects.get(id=serializer.data['id'], banger=request.user) except Bang.DoesNotExist: return response.Response({'id': ['Invalid bang ID']}, status=status.HTTP_404_NOT_FOUND) if bang.can_unbang: bang.delete() bangee = bang.bangee bangee.profile.bang_score -= 1 bangee.profile.save() return response.Response(None, status=status.HTTP_204_NO_CONTENT) else: return response.Response({'id': ['Cannot unbang at this time.']}, status=status.HTTP_403_FORBIDDEN) return response.response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def filtered_actions(self, request, pk=None): place = self.get_object( ) #gets the object using the slug given in the URL return response(place, status=status.HTTP_200_OK)
def post_data(request): """ Post data with content-type XML """ if request.method == 'POST': data = request.data if data: device = data['devices'] if not device: res = {'message': 'wrong format request data.'} return response(res, status=status.HTTP_400_BAD_REQUEST) for key, value in device.items(): if value == Device.TEMPERATURE_SENSOR: type = Device.TEMPERATURE_SENSOR unit = Device.DEGREE elif value == Device.VOLTAGE_METER: type = Device.VOLTAGE_METER unit = Device.VOLTAGE elif value == Device.CURRENT_METER: type = Device.CURRENT_METER unit = Device.AMPERE elif value == Device.POWER_METER: type = Device.POWER_METER unit = Device.WATT else: res = {'message': 'wrong device type.'} return response(res, status=status.HTTP_400_BAD_REQUEST) Device.objects.update_or_create(id=key, type=type, unit=unit) id_record = data['id'] record_time = data['record_time'] if not id_record or not record_time: res = { 'message': 'wrong format request data.', } return response(res, status=status.HTTP_400_BAD_REQUEST) record = Record(id=data['id'], record_time=data['record_time']) try: record.save() except Exception as e: res = {'message': 'failed.', 'err': e.args[0]} return response(res, status=status.HTTP_400_BAD_REQUEST) bulk_record = [] for element in data['data']: rec_device = Device.objects.get(id=element['device']) bulk_record.append( DeviceRecord( device=rec_device, record=record, value=element['value'], )) try: DeviceRecord.objects.bulk_create(bulk_record) except Exception as e: res = {'message': 'failed.', 'err': e.args[0]} return response(res, status=status.HTTP_400_BAD_REQUEST) queryset = DeviceRecord.objects.filter(record=record) serializer = DataSerializer(queryset, many=True) return response(serializer.data, status=200, content_type="application/json") return response(status=status.HTTP_400_BAD_REQUEST) return response(status=status.HTTP_400_BAD_REQUEST)