Django 从外部源接收 json post 请求



我写了一个视图函数,用于处理一个包含来自 django (labview) 之外的源的 json 数据的 post 请求。我只是在开始测试它,所以它看起来像这样

def post_entry(request):
    '''Process incoming json string
    '''
    if request.method == 'POST':
        post_data = request.body
    # Return a response
    return HttpResponse('data received OK')

我已经写了一个测试来测试这个,它通过得很好:

def test_post_entry_view_good_post_data(self):
    '''post_entry view should return a 200 status if valid
    '''
    data = {'DHTP Data': ['10', '50.296', '50.94', '50.418', '50.425', '50.431', '50.94'],
        'Test String': 'My Test String'}
    request_url = reverse('post_entry') 
    response = self.client.post(request_url, content_type='application/json', 
        data=dumps(data))
    # Should return a 200 response indicating ok
    self.assertEqual(response.status_code, 200)

但是,当Labview发布数据时,post_entry返回403禁止错误。我想这是由于不存在 csrf 令牌,但为什么在这种情况下测试通过?

测试客户端围绕 CSRF 功能工作。 请参阅 https://docs.djangoproject.com/en/1.9/ref/csrf/#testing

如果你的视图接受来自应用外部源的发布数据,则需要使用以下csrf_exempt使视图免于 CSRF 保护:

@csrf_exempt
def post_entry(request):
    '''Process incoming json string
    '''

如果要执行此操作,则应使用其他方法来验证请求

如果你的观点应该接受来自外部来源的POST,那么你需要验证请求,因为每个POST请求都需要有一个CSRF令牌(参考:CSRF)。因此,为了您的目的,您必须使用装饰器将视图从 CSRF 验证中免除@csrf_exempt并使用

类似令牌身份验证

最新更新