Search code examples
pythondjangotastypie

Tastypie: return html content in API response


I need to create an API that takes application/x-www-form-urlencoded data in POST data and returns a HTML content in response.

Now to serialize the urlencoded data I am calling following serializer from resource :

class urlencodeSerializer(Serializer):
formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencode']
content_types = {
    'json': 'application/json',
    'jsonp': 'text/javascript',
    'xml': 'application/xml',
    'yaml': 'text/yaml',
    'html': 'text/html',
    'plist': 'application/x-plist',
    'urlencode': 'application/x-www-form-urlencoded',
    }
def from_urlencode(self, data,options=None):
    """ handles basic formencoded url posts """
    qs = dict((k, v if len(v)>1 else v[0] )
    for k, v in urlparse.parse_qs(data).iteritems())
    return qs

def to_urlencode(self,content):
    pass

To specify the response format I have added this function in the resource :

    def determine_format(self, request):
        return 'text/html'

Now as I am trying to output the HTML response as below :

data = "<html><h1>Hello</h1></html>"
return HttpResponse(data, content_type='text/html', status=200)

I am getting following error :

Sorry, not implemented yet. Please append "?format=json" to your URL.

Can anybody suggest me what is wrong with this code and how to achieve the given requirement.


Solution

  • I have found the answer though not sure if its the correct way to do in tastypie :

    1. Normally return the bundle response from resource.

    2. Add following method in urlencodeSerializer

      def to_html(self,bundle, options):
           return prepare_html_from_bundle_data(bundle.data)