Allow routes to only return a body and headers

This commit is contained in:
Miguel Grinberg
2022-07-31 16:49:21 +01:00
parent 8177b9c7f1
commit 16f3775fa2
2 changed files with 59 additions and 1 deletions

View File

@@ -944,7 +944,14 @@ class Microdot():
if res is None:
res = f(req, **req.url_args)
if isinstance(res, tuple):
res = Response(*res)
body = res[0]
if isinstance(res[1], int):
status_code = res[1]
headers = res[2] if len(res) > 2 else {}
else:
status_code = 200
headers = res[1]
res = Response(body, status_code, headers)
elif not isinstance(res, Response):
res = Response(res)
for handler in self.after_request_handlers:

View File

@@ -111,6 +111,57 @@ class TestMicrodot(unittest.TestCase):
self.assertTrue(fd.response.endswith(
b'\r\n\r\n' + method.encode()))
def test_tuple_responses(self):
app = Microdot()
@app.route('/body')
def one(req):
return 'one'
@app.route('/body-status')
def two(req):
return 'two', 202
@app.route('/body-headers')
def three(req):
return '<p>three</p>', {'Content-Type': 'text/html'}
@app.route('/body-status-headers')
def four(req):
return '<p>four</p>', 202, {'Content-Type': 'text/html'}
mock_socket.clear_requests()
fd = mock_socket.add_request('GET', '/body')
self._add_shutdown(app)
app.run()
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
self.assertTrue(fd.response.endswith(b'\r\n\r\none'))
mock_socket.clear_requests()
fd = mock_socket.add_request('GET', '/body-status')
self._add_shutdown(app)
app.run()
self.assertTrue(fd.response.startswith(b'HTTP/1.0 202 N/A\r\n'))
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
self.assertTrue(fd.response.endswith(b'\r\n\r\ntwo'))
mock_socket.clear_requests()
fd = mock_socket.add_request('GET', '/body-headers')
self._add_shutdown(app)
app.run()
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
self.assertIn(b'Content-Type: text/html\r\n', fd.response)
self.assertTrue(fd.response.endswith(b'\r\n\r\n<p>three</p>'))
mock_socket.clear_requests()
fd = mock_socket.add_request('GET', '/body-status-headers')
self._add_shutdown(app)
app.run()
self.assertTrue(fd.response.startswith(b'HTTP/1.0 202 N/A\r\n'))
self.assertIn(b'Content-Type: text/html\r\n', fd.response)
self.assertTrue(fd.response.endswith(b'\r\n\r\n<p>four</p>'))
def test_before_after_request(self):
app = Microdot()