Skip to content
This repository has been archived by the owner on Nov 30, 2023. It is now read-only.

Commit

Permalink
Enable Pythonic access of Request attributes w/ getitem (#129)
Browse files Browse the repository at this point in the history
  • Loading branch information
awan1 authored and Jon Wayne Parrott committed Jun 20, 2017
1 parent 270149b commit deb3444
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
38 changes: 38 additions & 0 deletions tests/request_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
12 changes: 12 additions & 0 deletions webapp2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit deb3444

Please sign in to comment.