djangochannelsrestframework
djangochannelsrestframework copied to clipboard
Batter handling of malformed WS message bodies.
Is your feature request related to a problem? Please describe.
When sending messages, if the expected data for a given action is not present at the moment the consumer closes, rather than responding with an error
message.
Describe the solution you'd like Response with an error json message when:
- malformed JSON is sent over the websocket connection
- the action keyword is missing
- the action method expects a kwarge that was not provided as part of the action json
I think I will help you do this. Please write some notes about how you want it to be implemented
@jakiro2017 That would be great.
the action keyword is missing
might be best to check in AsyncAPIConsumer.receive_json
update the pop to return None if the key is not there. Then in handle_action
inside the try
block check that it is not None if it is raise the MethodNotAllowed
error.
the action method expects a kwarge that was not provided as part of the action json
To produce a nice error message you could use
from inspect import signature
sig = signature(method)
then validate that all the args in the sig match up to args in the message.
this would could be place somere here: https://github.com/hishnash/djangochannelsrestframework/blob/master/djangochannelsrestframework/consumers.py#L140
Then you could raise a DRF 400 error.
malformed JSON is sent over the websocket connection
This is a little more complex complex since Django Channels is doing the json decoding we need to move that try catch up one more level.
def receive(self, text_data=None, bytes_data=None, **kwargs):
try:
super().receive(text_data=text_data, bytes_data, **kwargs)
except ...
Here you need to capture the json decoding and instead return the proper DRF error response.