Add some more response types
[fwx] / phial.py
index bce8979..f4da0dd 100644 (file)
--- a/phial.py
+++ b/phial.py
@@ -1,4 +1,5 @@
 import collections
+import json
 
 Request = collections.namedtuple(
     'Request',
@@ -18,7 +19,7 @@ _Response = collections.namedtuple(
 )
 
 class Response(_Response):
-    def __new__(cls, **kwargs):
+    def __new__(cls, content, **kwargs):
         status = kwargs.pop('status', 200)
         assert isinstance(status, int)
 
@@ -28,8 +29,6 @@ class Response(_Response):
         extra_headers = kwargs.pop('extra_headers', ())
         assert isinstance(extra_headers, tuple)
 
-        content = kwargs.pop('content')
-
         assert len(kwargs) == 0
 
         return super().__new__(
@@ -46,6 +45,42 @@ class Response(_Response):
             ('Content-Type', self.content_type),
         )
 
+class HTMLResponse(Response):
+    def __new__(cls, content, **kwargs):
+        assert 'content_type' not in kwargs
+
+        return super().__new__(
+            cls,
+            content,
+            content_type='text/html',
+            **kwargs,
+        )
+
+class JSONResponse(Response):
+    def __new__(cls, content_json, **kwargs):
+        assert 'content_type' not in kwargs
+        assert 'content' not in kwargs
+
+        self = super().__new__(
+            cls,
+            content=json.dumps(content_json),
+            content_type='application/json',
+            **kwargs,
+        )
+        self.content_json = content_json
+        return self
+
+class TextResponse(Response):
+    def __new__(cls, content, **kwargs):
+        assert 'content_type' not in kwargs
+
+        return super().__new__(
+            cls,
+            content,
+            content_type='text/plain',
+            **kwargs,
+        )
+
 def _get_status(response):
     return {
         200: '200 OK',