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 3 months, 2 weeks ago
  2. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  3. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months, 1 week ago
  4. Help text hyperlinks by sa2812 12 months ago
  5. Stuff by NixonDash 1 year, 2 months ago

Comments

Please login first before commenting.