From 8d1171df29d5e7c1d5d6ffd9eb81eaf13365037c Mon Sep 17 00:00:00 2001 From: Martin Zimmermann Date: Tue, 5 Nov 2013 12:35:17 +0100 Subject: [PATCH] improve request decoding and json parsing --- isso/utils/__init__.py | 4 ++-- isso/views/comment.py | 4 ++-- specs/test_comment.py | 14 ++++++++++++++ specs/test_cors.py | 0 4 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 specs/test_cors.py diff --git a/isso/utils/__init__.py b/isso/utils/__init__.py index d707b99..de3be2b 100644 --- a/isso/utils/__init__.py +++ b/isso/utils/__init__.py @@ -95,11 +95,11 @@ class Bloomfilter: class JSONRequest(Request): if werkzeug.version.startswith("0.8"): - def get_data(self): + def get_data(self, **kw): return self.data.decode('utf-8') def get_json(self): try: - return json.loads(self.get_data().decode('utf-8')) + return json.loads(self.get_data(as_text=True)) except ValueError: raise BadRequest('Unable to read JSON request') diff --git a/isso/views/comment.py b/isso/views/comment.py index 01c7449..1566700 100644 --- a/isso/views/comment.py +++ b/isso/views/comment.py @@ -55,7 +55,7 @@ def new(app, environ, request, uri): for field in set(data.keys()) - set(['text', 'author', 'website', 'email', 'parent']): data.pop(field) - if not data.get("text"): + if "text" not in data or data["text"] is None or len(data["text"]) < 3: raise BadRequest("no text given") if "id" in data and not isinstance(data["id"], int): @@ -162,7 +162,7 @@ def single(app, environ, request, id): if request.method == 'PUT': data = request.get_json() - if data.get("text") is not None and len(data['text']) < 3: + if "text" not in data or data["text"] is None or len(data["text"]) < 3: raise BadRequest("no text given") for key in set(data.keys()) - set(["text", "author", "website"]): diff --git a/specs/test_comment.py b/specs/test_comment.py index 07ef3a9..3b4818f 100644 --- a/specs/test_comment.py +++ b/specs/test_comment.py @@ -1,3 +1,5 @@ +# -*- encoding: utf-8 -*- + from __future__ import unicode_literals @@ -92,6 +94,18 @@ class TestComments(unittest.TestCase): assert rv["mode"] == 1 assert rv["text"] == '

Lorem ipsum ...

\n' + def textCreateWithNonAsciiText(self): + + rv = self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Здравствуй, мир!'})) + + assert rv.status_code == 201 + assert any(filter(lambda header: header[0] == 'Set-Cookie', rv.headers)) + + rv = loads(rv.data) + + assert rv["mode"] == 1 + assert rv["text"] == '

Здравствуй, мир!

\n' + def testCreateMultiple(self): a = self.post('/new?uri=test', data=json.dumps({'text': '...'})) diff --git a/specs/test_cors.py b/specs/test_cors.py new file mode 100644 index 0000000..e69de29