Skip to content

Commit

Permalink
Merge pull request #218 from onefinestay/http_response_type
Browse files Browse the repository at this point in the history
require string responses for http
  • Loading branch information
davidszotten committed Mar 11, 2015
2 parents f539d9c + 2f46ef8 commit 24fde3a
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 5 deletions.
7 changes: 6 additions & 1 deletion docs/built_in_extensions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,12 @@ Nameko's HTTP entrypoint supports simple GET and POST:
received: post body
The HTTP entrypoint is built on top of `werkzeug <http://werkzeug.pocoo.org/>`_. Service methods can return specific status codes and headers, or a :class:`werkzeug.wrappers.Response` object:
The HTTP entrypoint is built on top of `werkzeug <http://werkzeug.pocoo.org/>`_. Service methods must return one of:

- a string, which becomes the response body
- a 2-tuple ``(status code, response body)``
- a 3-tuple ``(status_code, headers dict, response body)``
- an instance of :class:`werkzeug.wrappers.Response`

.. literalinclude:: examples/advanced_http.py

Expand Down
3 changes: 2 additions & 1 deletion docs/examples/http.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# http.py

import json
from nameko.web.handlers import http

class HttpService(object):

@http('GET', '/get/<int:value>')
def get_method(self, value):
return {'value': value}
return json.dumps({'value': value})

@http('POST', '/post')
def do_post(self, body):
Expand Down
5 changes: 4 additions & 1 deletion nameko/web/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@ def response_from_result(result):
payload = result
status = 200

if not isinstance(payload, basestring):
raise TypeError("Payload must be a string. Got `{!r}`".format(payload))

return Response(
unicode(payload),
payload,
status=status,
headers=headers,
)
Expand Down
10 changes: 8 additions & 2 deletions test/web/test_http_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def test_get(web_session):

def test_post(web_session):
rv = web_session.post('/post', json={
'value': 23,
'value': 'foo',
})
assert rv.text == "23"
assert rv.text == "foo"


def test_custom_response(web_session):
Expand Down Expand Up @@ -90,3 +90,9 @@ def test_broken_method_expected(web_session):
rv = web_session.get('/fail_expected')
assert rv.status_code == 400
assert "ValueError: oops" in rv.text


def test_bad_payload(web_session):
rv = web_session.post('/post', json={'value': 23})
assert rv.status_code == 500
assert "Error: TypeError: Payload must be a string. Got `23`" in rv.text

0 comments on commit 24fde3a

Please sign in to comment.