我有Django中间件来处理POST请求。
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, req):
response = self.get_response(req)
# want to do something with 'r.body',
# but it is not able to be read
return response
由于请求主体已经在get_response
中读取,因此我无法在中间件中再次读取它。
尝试了copy.copy()
,但没有成功,因为复制的流引用了原始流的相同对象。copy.deepcopy()
引发异常。
如何在中间件中处理POST数据?
我想处理所有请求,所以在每个视图中实现逻辑并不理想。
找到解决方案
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, req):
req.body # just add this line BEFORE get_response
response = self.get_response(req)
return response