From deb34447ef8927c940bed2d80c7eec75f9f01be8 Mon Sep 17 00:00:00 2001 From: Adrian Wan Date: Tue, 20 Jun 2017 13:54:32 -0700 Subject: [PATCH] Enable Pythonic access of Request attributes w/ getitem (#129) --- tests/request_test.py | 38 ++++++++++++++++++++++++++++++++++++++ webapp2.py | 12 ++++++++++++ 2 files changed, 50 insertions(+) diff --git a/tests/request_test.py b/tests/request_test.py index c11066e..2cde5cb 100644 --- a/tests/request_test.py +++ b/tests/request_test.py @@ -241,6 +241,44 @@ def test_get_with_POST(self): res = req.get('8', default_value='9') self.assertEqual(res, '9') + def test_getitem(self): + req = webapp2.Request.blank('/?1=2&1=3&3=4', POST='5=6&7=8') + + res = req['1'] + self.assertEqual(res, '2') + + res = req['8'] + self.assertEqual(res, '') + + def test_getitem_with_POST(self): + req = webapp2.Request.blank('/?1=2&1=3&3=4', POST={5: 6, 7: 8}) + + res = req['1'] + self.assertEqual(res, '2') + + res = req['8'] + self.assertEqual(res, '') + + def test_getitem_with_square_brackets(self): + req = webapp2.Request.blank('/endpoint?x[1]=3&a=1&a=2&b=0') + + res = req['x'] + self.assertEqual(res, '') + + res = req['x[1]'] + self.assertEqual(res, '3') + + def test_setitem(self): + req = webapp2.Request.blank('/?1=2&1=3&3=4', POST='5=6&7=8') + + # Existing key + with self.assertRaises(TypeError): + req['1'] = '7' + + # New key + with self.assertRaises(TypeError): + req['8'] = '7' + def test_arguments(self): req = webapp2.Request.blank('/?1=2&3=4', POST='5=6&7=8') diff --git a/webapp2.py b/webapp2.py index 1d9317a..e48e7bf 100755 --- a/webapp2.py +++ b/webapp2.py @@ -211,6 +211,18 @@ def get(self, argument_name, default_value='', allow_multiple=False): else: return default_value + def __getitem__(self, argument_name): + """Provides dict-like access to attributes. + + :param argument_name: + The name of the query or POST argument. + :returns: + Return the value with the given name given in the request. If there + are multiple values, this will only return the first one. Use + `get_all()` to get multiple values. + """ + return self.get(argument_name) + def get_all(self, argument_name, default_value=None): """Returns a list of query or POST arguments with the given name.