python.django.best-practice.json_response.use-json-response

profile photo of semgrepsemgrep
Author
9,905
Download Count*

Use JsonResponse instead

Run Locally

Run in CI

Defintion

rules:
  - id: use-json-response
    patterns:
      - pattern-inside: |
          def $X(...):
            ...
      - pattern: |
          $Y = json.dumps(...)
          ...
          django.http.HttpResponse($Y, ...)
    message: Use JsonResponse instead
    languages:
      - python
    severity: ERROR
    metadata:
      category: best-practice
      technology:
        - django
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

json_response.py

from django.http import HttpResponse
import json

def foo():
    # ruleid:use-json-response
    dump = json.dumps({})
    return HttpResponse(dump, content_type='application/json')

def foo1():
    # ruleid:use-json-response
    dump = json.dumps({})
    x = HttpResponse(dump, content_type='application/json')