From 3b6b3173776829986577133919e170a8e3f171f2 Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Sun, 4 Aug 2024 14:55:32 -0500 Subject: [PATCH] feat: add `util.get_form_data()` convenience function --- src/wuttaweb/util.py | 23 ++++++++++++++++++++++- tests/test_util.py | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/wuttaweb/util.py b/src/wuttaweb/util.py index 3275301..1cf7804 100644 --- a/src/wuttaweb/util.py +++ b/src/wuttaweb/util.py @@ -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, diff --git a/tests/test_util.py b/tests/test_util.py index d492943..c68d42c 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -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'})