Login

JSONRequestMiddleware adds a .json() method to your HttpRequests

Author:
cdcarter
Posted:
January 5, 2024
Language:
Python
Version:
3.2
Score:
0 (after 0 ratings)

add JSONRequestMiddleware to your enabled middleware in Django settings. Now, in your view functions, you can call request.json() to get a parsed json body! json is consumed lazily, and cached.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import json
from functools import lru_cache, partial
from django.http import HttpRequest

def _lazy_json(request):
    return json.loads(request.body)

def JSONRequestMiddleware(get_response):
    def middleware(request: HttpRequest):
        request.json = lru_cache(partial(_lazy_json, request))
        response = get_response(request)
        return response

    return middleware

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
  2. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  3. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  4. Help text hyperlinks by sa2812 1 year, 5 months ago
  5. Stuff by NixonDash 1 year, 7 months ago

Comments

Please login first before commenting.