From f73dc7c3cf9a12897e7b9e5a0cdadef9a10de961 Mon Sep 17 00:00:00 2001 From: shagi Date: Tue, 2 Nov 2021 07:45:15 +0100 Subject: [PATCH] Add GET support to AjaxCommandMixin --- changelog.md | 5 +++-- gas/views.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index 28bbb82..cbd2cb6 100644 --- a/changelog.md +++ b/changelog.md @@ -1,9 +1,10 @@ Changelog ========= -0.7.2 (Unreleased) ------------------- +0.7.2 +----- +* Add GET support to AjaxCommandMixin * Enhanced json encoder, available in AjaxCommandsMixin * Add Shakarina to collaborators, thanks! diff --git a/gas/views.py b/gas/views.py index b96dd11..86c563b 100644 --- a/gas/views.py +++ b/gas/views.py @@ -17,6 +17,32 @@ from . import utils class AjaxCommandsMixin: + """ + Mixin class for views with javascript interaction. + + Allows defining several commands (POST or GET) on a diferent + method per command. A request is identified as a command if it has + a `command` field in the request. + + To react to a POST command define a method starting with `do_`. + For example a request with a command named `store_answer` will be + processed in the method `do_store_answer`. + + Similarly, to react to a GET command define a method starting with + `send_`. For example a request with a command named `user_list` will be + processed in the method `send_user_list`. + + If the request has no command then it will be processed like in + any other DJango view. + + If the request has a command not defined in the view it will get a + 400 response (Bad Request). + + The helper `render_json` method allows returning an + application/json with automatic serialization of the given python + data. It uses the extended json encoder allowing serialization of + queryets, lazy strings, dates, etc. + """ def post(self, request, *args, **kwargs): if 'command' in self.request.POST: command_processor = getattr(self, 'do_{0}'.format(self.request.POST['command']), None) @@ -28,6 +54,17 @@ class AjaxCommandsMixin: handler = getattr(super(), 'post', self.http_method_not_allowed) return handler(request, *args, **kwargs) + def get(self, request, *args, **kwargs): + if 'command' in self.request.GET: + command_processor = getattr(self, 'send_{0}'.format(self.request.GET['command']), None) + if command_processor is not None: + return command_processor() + else: + return HttpResponseBadRequest() + else: + handler = getattr(super(), 'get', self.http_method_not_allowed) + return handler(request, *args, **kwargs) + def render_json(self, data, encoder=utils.JSONEncoder): return HttpResponse( json.dumps(data, indent=2, cls=encoder),