Skip to content

Conditionally render JSONP #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions rest_framework_jsonp/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class JSONPRenderer(JSONRenderer):
wrapping the json output in a callback function.
"""

media_type = 'application/javascript'
js_media_type = 'application/javascript'
format = 'jsonp'
callback_parameter = 'callback'
default_callback = 'callback'
Expand All @@ -24,9 +24,10 @@ def get_callback(self, renderer_context):
"""
Determine the name of the callback to wrap around the json output.
"""
request = renderer_context.get('request', None)
request = renderer_context.get('request')
params = request and get_query_params(request) or {}
return params.get(self.callback_parameter, self.default_callback)
return (params[self.callback_parameter] or self.default_callback
if self.callback_parameter in params else None)

def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Expand All @@ -39,4 +40,6 @@ def render(self, data, accepted_media_type=None, renderer_context=None):
callback = self.get_callback(renderer_context)
json = super(JSONPRenderer, self).render(data, accepted_media_type,
renderer_context)
return callback.encode(self.charset) + b'(' + json + b');'
if accepted_media_type == self.js_media_type or callback is not None:
json = callback.encode(self.charset) + b'(' + json + b');'
return json