Add GET support to AjaxCommandMixin

This commit is contained in:
Ales (Shagi) Zabala Alava 2021-11-02 07:45:15 +01:00
parent 90c2fb381b
commit f73dc7c3cf
2 changed files with 40 additions and 2 deletions

View File

@ -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!

View File

@ -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),