问题描述
我有一个正常的Django 1.8站点,并且我想使用django-rest-framework添加一个RESTful API。我想支持以CSV和JSON格式进行渲染,并且对如何执行此操作感到困惑。
I have a working Django 1.8 site, and I want to add a RESTful API using django-rest-framework. I would like to support rendering to CSV and JSON formats, and am puzzling over how to do this.
在 api / urls.py
中我有这个:
from django.conf.urls import url, include
from rest_framework import routers
from rest_framework.urlpatterns import format_suffix_patterns
import views
router = routers.DefaultRouter()
urlpatterns = [
url(r'^organisation/$', views.organisation),
]
urlpatterns = format_suffix_patterns(urlpatterns,
allowed=['json', 'csv'])
这在 api / views.py
:
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@api_view(['GET'])
def organisation(request, format=None):
code = request.query_params.get('code', None)
print 'format', format
organisation = Organisation.objects.get(code=code)
serializer = OrgSerializer(organisation)
data = serializer.data
return JSONResponse(data)
但是如果我去 api / 1.0 / organisation.csv?code = 123
,我仍然看到:
But if I go to api/1.0/organisation.csv?code=123
, I still see:
format json
在控制台中。
我在做什么错?设法捕获格式后,应该如何返回CSV? (我怀疑我可能已经通过编写自己的 JSONResponse
做错了。)
What am I doing wrong? And how should I return CSV once I have managed to capture the format? (I suspect I'm probably doing the wrong thing by writing my own JSONResponse
, already.)
推荐答案
知道了。诀窍是要安装,然后在设置中添加以下内容:
Got it. The trick is to install djangorestframework-csv, then add the following in settings:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework_csv.renderers.CSVRenderer',
),
}
然后在 views.py
中废弃 JSONResponse
函数,然后执行返回响应(serializer.data)
。最后很容易。
And then scrap the JSONResponse
function in views.py
and just do return Response(serializer.data)
instead. Very easy in the end.
这篇关于从django-rest-framework返回CSV格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!