DRF:在自定义渲染器中获取请求对象
DRF: Get request object in custom renderer
我正在使用 django==1.10 和 djangorestframework==3.4.6 构建服务器端
我已经构建了一个 JSONRenderer:
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
meta_fields = ["temp_save", "subject", "visit"]
a = {"fields": {}}
for k in data:
try:
meta_fields.index(k) # Crashes with ValueError if not found
a[k] = data[k]
except ValueError:
a["fields"][k] = data[k]
return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context)
问题:是否可以获取视图request
对象?我特别想访问 urls 参数(例如 request.kwargs['pk']
您可以通过以下方式从 renderer_context
获取请求。
request = renderer_context['request']
您的代码:
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
request = renderer_context['request'] or None
meta_fields = ["temp_save", "subject", "visit"]
a = {"fields": {}}
for k in data:
try:
meta_fields.index(k) # Crashes with ValueError if not found
a[k] = data[k]
except ValueError:
a["fields"][k] = data[k]
return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context)
也许这会对你有所帮助。
我正在使用 django==1.10 和 djangorestframework==3.4.6 构建服务器端
我已经构建了一个 JSONRenderer:
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
meta_fields = ["temp_save", "subject", "visit"]
a = {"fields": {}}
for k in data:
try:
meta_fields.index(k) # Crashes with ValueError if not found
a[k] = data[k]
except ValueError:
a["fields"][k] = data[k]
return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context)
问题:是否可以获取视图request
对象?我特别想访问 urls 参数(例如 request.kwargs['pk']
您可以通过以下方式从 renderer_context
获取请求。
request = renderer_context['request']
您的代码:
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
request = renderer_context['request'] or None
meta_fields = ["temp_save", "subject", "visit"]
a = {"fields": {}}
for k in data:
try:
meta_fields.index(k) # Crashes with ValueError if not found
a[k] = data[k]
except ValueError:
a["fields"][k] = data[k]
return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context)
也许这会对你有所帮助。