Условно возвращайте JSON или XML ответ из представления Django django-rest-framework, основанного на классах
Как получить ответ ap на тело запроса, передав output_format = 'json' или 'xml'.
Он возвращает только один тип ответа. Как я могу получить оба ответа в соответствии с условием.
Ниже представлен мой код.
djangorestframework==3.13.1
Setting.py
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework_xml.renderers.XMLRenderer',
]
}
views.py
class AddressAPI(APIView):
renderer_classes = (XMLRenderer, JSONRenderer)
def post(self, request):
try:
serializer = GeoLocationSerializer(data=request.data)
if serializer.is_valid():
address = serializer.data['address']
output_format = serializer.data['output_format']
address_body = format_address(address)
url = f"https://maps.googleapis.com/maps/api/geocode/json?address={address_body}&key={api_key}"
response = requests.request("GET", url)
source = response.text
data = json.loads(source)
for source in data['results']:
if output_format == 'json' or output_format == 'JSON':
# print(serializer.data)
return Response({
'coordinates' : source['geometry']['location'],
'address' : address,
})
elif output_format == 'xml' or output_format == 'XML':
return Response({
'coordinates' : source['geometry']['location'],
'address' : address,
})
else:
return Response({
'message' : 'Invalid output_format'
})
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)