From 32c842f06f109f68a03d2c182393225198b181f4 Mon Sep 17 00:00:00 2001 From: Kevin McCarthy Date: Thu, 5 Jun 2014 17:56:34 -1000 Subject: [PATCH] Fix bug that was causing POSTs missing a content-type header to 500 Closes #141 --- httpbin/helpers.py | 6 +++--- test_httpbin.py | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/httpbin/helpers.py b/httpbin/helpers.py index 65d8a6d..1e350a8 100644 --- a/httpbin/helpers.py +++ b/httpbin/helpers.py @@ -75,13 +75,12 @@ def json_safe(string, content_type='application/octet-stream'): suitable for binary data, some additional encoding was necessary; "data" URL scheme was chosen for its simplicity. """ - try: _encoded = json.dumps(string) return string except (ValueError, TypeError): return b''.join([ - b'data:', + b'data:', content_type.encode('utf-8'), b';base64,', base64.b64encode(string) @@ -94,7 +93,8 @@ def get_files(): files = dict() for k, v in request.files.items(): - val = json_safe(v.read(), request.files[k].content_type) + content_type = request.files[k].content_type or 'application/octet-stream' + val = json_safe(v.read(), content_type) if files.get(k): if not isinstance(files[k], list): files[k] = [files[k]] diff --git a/test_httpbin.py b/test_httpbin.py index 4e36ef2..bedd41c 100755 --- a/test_httpbin.py +++ b/test_httpbin.py @@ -4,6 +4,7 @@ import base64 import unittest from werkzeug.http import parse_dict_header from hashlib import md5 +from six import BytesIO import httpbin @@ -34,16 +35,27 @@ class HttpbinTestCase(unittest.TestCase): content_type='application/octet-stream') self.assertEqual(response.status_code, 200) - def test_post_file_text(self): + def test_post_body_text(self): with open('httpbin/core.py') as f: response = self.app.post('/post', data={"file": f.read()}) self.assertEqual(response.status_code, 200) - def test_post_file_binary(self): + def test_post_body_binary(self): with open('httpbin/core.pyc','rb') as f: response = self.app.post('/post', data={"file": f.read()}) self.assertEqual(response.status_code, 200) + def test_post_file_with_missing_content_type_header(self): + # I built up the form data manually here because I couldn't find a way + # to convince the werkzeug test client to send files without the + # content-type of the file set. + response = self.app.post( + '/post', + content_type='multipart/form-data; boundary=bound', + data = '--bound\r\nContent-Disposition: form-data; name="media"; filename="test.bin"\r\n\r\n\xa5\xc6\n--bound--\r\n' + ) + self.assertEqual(response.status_code, 200) + def test_set_cors_headers_after_request(self): response = self.app.get('/get') self.assertEqual(response.headers.get('Access-Control-Allow-Origin'), '*')