我有一个非常简单的Django REST安装,其中包含一个包含4个字段的表。 我可以毫无问题地与API进行交互,但是当我进行GET调用时,我得到的JSON在开头就有这些神秘的5个字符,它们打破了JSON。
djangorestframework(2.3.14) Python(2.7)
models.py
class SensorData(models.Model):
string = models.CharField(max_length=255)
sensordata = models.CharField(max_length=255, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'sensor_data'
serialzers.py
from rest_framework import serializers
from models import SensorData
class SensorDataSerializer(serializers.ModelSerializer):
"""
Serializer for test API endpoint
"""
timestamp = serializers.DateTimeField(format='%Y-%m-%d')
class Meta:
model = SensorData
fields = ('id', 'string', 'sensordata', 'timestamp')
views.py
from rest_framework import viewsets
from serializers import SensorDataSerializer
from models import SensorData
class SensorDataViewSet(viewsets.ModelViewSet):
"""
API endpoint for test sensor data
"""
queryset = SensorData.objects.all()
serializer_class = SensorDataSerializer
settings.py
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.ModelSerializer',
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
)
}
我的回复:
)]}',
[{"id": 1, "string": "Jassen", "sensordata": "test", "timestamp": "2014-07-15"}]
答案 0 :(得分:2)
我找到了Djangular的根本原因,它有一个中间件将坏字符附加到JSON的开头。
'djangular.middleware.AngularJsonVulnerabilityMiddleware'
希望能节省一些时间。