1
0
Fork 0

feat: add util.get_form_data() convenience function

This commit is contained in:
Lance Edgar 2024-08-04 14:55:32 -05:00
parent 26d44390a5
commit 3b6b317377
2 changed files with 49 additions and 1 deletions

View file

@ -21,12 +21,33 @@
#
################################################################################
"""
Utilities
Web Utilities
"""
import importlib
def get_form_data(request):
"""
Returns the effective form data for the given request.
Mostly this is a convenience, which simply returns one of the
following, depending on various attributes of the request.
* :attr:`pyramid:pyramid.request.Request.POST`
* :attr:`pyramid:pyramid.request.Request.json_body`
"""
# nb. we prefer JSON only if no POST is present
# TODO: this seems to work for our use case at least, but perhaps
# there is a better way? see also
# https://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html#pyramid.request.Request.is_xhr
if not request.POST and (
getattr(request, 'is_xhr', False)
or request.content_type == 'application/json'):
return request.json_body
return request.POST
def get_libver(
request,
key,

View file

@ -263,3 +263,30 @@ class TestGetLibUrl(TestCase):
self.config.setdefault('wuttaweb.liburl.bb_vue_fontawesome', '/lib/vue-fontawesome.js')
url = util.get_liburl(self.request, 'bb_vue_fontawesome')
self.assertEqual(url, '/lib/vue-fontawesome.js')
class TestGetFormData(TestCase):
def setUp(self):
self.config = WuttaConfig()
def make_request(self, **kwargs):
kwargs.setdefault('wutta_config', self.config)
kwargs.setdefault('POST', {'foo1': 'bar'})
kwargs.setdefault('json_body', {'foo2': 'baz'})
return testing.DummyRequest(**kwargs)
def test_default(self):
request = self.make_request()
data = util.get_form_data(request)
self.assertEqual(data, {'foo1': 'bar'})
def test_is_xhr(self):
request = self.make_request(POST=None, is_xhr=True)
data = util.get_form_data(request)
self.assertEqual(data, {'foo2': 'baz'})
def test_content_type(self):
request = self.make_request(POST=None, content_type='application/json')
data = util.get_form_data(request)
self.assertEqual(data, {'foo2': 'baz'})