'How do I use Django piston to return a response in text/plain?

I want to NOT serialize anything. I just want to return what is equivalent to HttpResponse(blah)



Solution 1:[1]

Sounds like you want a string emitter, and not one of the built-in JSONEmitter, XMLEmitter, etc.

Have a look at the docs for emitters: https://bitbucket.org/jespern/django-piston/wiki/Documentation

And the existing emitter definitions here: https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/emitters.py

A definition of a plain text emitter might look like this:

from piston.emitters import Emitter
from piston.utils import Mimer    

class TextEmitter(Emitter):
    def render(self, request):
        return self.construct()
Emitter.register('text', TextEmitter)
Mimer.register('text', None, ('text/plain',))

You'd get your resource to use this emitter in your urls.py like so:

urlpatterns = patterns('',
   url(r'^blogposts$', resource_here, { 'emitter_format': 'text' }),
)

Solution 2:[2]

To add on to user85461's answer, when you make a text emitter, you'll want to also make a text Mimer. I wrote the following code with works with Piston 0.2.2

from piston.emitters import Emitter
from piston.utils import Mimer

class TextEmitter(Emitter):
    def render(self, request):
        return self.construct()
Emitter.register('text', TextEmitter, ('text/plain',))
Mimer.register(lambda x: QueryDict(x), ('text/plain',))

Add this snippet somewhere that will get run before your handlers. I put it in my API urls.py above where I created my Resources with

resource_handler = Resource(handler=SomeHandler)

Solution 3:[3]

in your view:

class HttpResponsePlain(django.http.HttpResponse):

    def serialize(self):            return self.content
    def serialize_headers(self):    return ''

return HttpResponsePlain(content = 'That is plain text response!')

Solution 4:[4]

Simplest way I found, from the Django docs:

HttpResponse("Text only, please.", content_type="text/plain")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Streeter
Solution 2 Streeter
Solution 3
Solution 4 Aidan Feldman