django中间件使帖子请求空白

时间:2016-02-18 06:20:40

标签: python django api middleware

如果我使用中间件,我发送的发布数据将被捕获为空白,如果我从settings.py文件中删除中间件,则返回发布数据。我究竟做错了什么。

enter image description here

当我删除中间件

时,这是正确的结果

enter image description here

这是中间件代码:缩进可能在这里错误

class CheckAuthorization(object):
def process_request(self, request):
    getKey = request.POST.get('authKey')
    token = request.POST.get('token')
    full_path = request.get_full_path()
    if getKey is not None and getKey != '' and full_path != "/users/splash/":
        try:
            auth = TblAutherization.objects.get(secret_key = request.POST.get('authKey'))
        except TblAutherization.DoesNotExist:
            response = JsonResponse({'Status':'Error','Response code': 107,'Message':full_path})
            return HttpResponse(response, content_type='application/json')
    else:
        return None
    if token is not None and token != '' and  'settoken' in request.session and full_path != "/users/splash/":
        try:
            auth = TblLoginAuth.objects.get(token = request.POST.get('token'))
        except TblLoginAuth.DoesNotExist:
            response = JsonResponse({'Status':'Error','Response code': 107,'Message':'Invalid Request'})
            return HttpResponse(response, content_type='application/json')
    else:
        return None 

views.py

def splash(request):
if request.method == 'POST':
    try:
        appId = request.POST.get('appId')
    except: 
        return Response({'Status':appId})

    gcmToken = request.POST.get('gcmToken')
    deviceType = request.POST.get('deviceType')
    userId = request.POST.get('userId')
    loginStatus = request.POST.get('loginStatus')
    appType=request.POST.get('appType')
    return Response({'appId':appId,'gcmToken':gcmToken,'deviceType':deviceType})
else:
    return Response({'appId':appId,'gcmToken':gcmToken,'deviceType':deviceType})

除非我尝试使用

,否则它甚至不会进入

2 个答案:

答案 0 :(得分:2)

当我实现日志记录中间件时,我遇到了同样的问题。如果您尝试在中间件中访问它,Django似乎会从POST dict中删除所有数据。 Idk如果它是一个错误或功能,但我提出了临时解决方案:您可以使用request.body来获取数据。

body = request.body.decode('utf-8')  # in python 3 json.loads only accepts unicode strings 
body = json.loads(body)
content = body['content']

答案 1 :(得分:0)

我不是中间件专家,但我知道我们在项目中使用它,而且我看到的关键区别是你没有回复成功案例的回复。所以我看到你试过:auth = blah,但是你没有使用它。所以你总是通过HttpResponse()返回None或错误。成功怎么样?