Best way to validate and sanitize JSON data in Django Channels consumer? #2192
-
|
Hey everyone 👋 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hey! 👋 class MessageSchema(BaseModel): async def receive_json(self, content): ✅ This keeps validation clean |
Beta Was this translation helpful? Give feedback.
Hey! 👋
Yeah, manually checking fields can get messy quickly. A common approach is to use Pydantic or Django Forms/Serializers even inside a Channels consumer.
Example with Pydantic:
from pydantic import BaseModel, ValidationError
class MessageSchema(BaseModel):
action: str
payload: dict
async def receive_json(self, content):
try:
data = MessageSchema(**content)
# proceed with validated data
await self.send_json({"type": "success", "message": "Valid data!"})
except ValidationError as e:
await self.send_json({"type": "error", "message": str(e)})
✅ This keeps validation clean
✅ Prevents processing invalid data
✅ Keeps the connection alive while sending structured error messages
So in short: …