Django 从外部源接收 json post 请求
Django receiving json post request from external source
我编写了一个视图函数来处理 post 请求,其中包含来自 django (labview) 外部源的 json 数据。我只是在开始测试它,所以它看起来像这样
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 posts 数据 post_entry
returns 出现 403 forbidden 错误。我想这是因为没有 csrf 令牌,但为什么在这种情况下测试通过了?
测试客户端围绕 CSRF 功能工作。参见 https://docs.djangoproject.com/en/1.9/ref/csrf/#testing
如果您要有一个视图接受来自应用程序外部来源的 post 数据,您需要使用 csrf_exempt:[=12= 让您的视图免于 CSRF 保护]
@csrf_exempt
def post_entry(request):
'''Process incoming json string
'''
如果您要这样做,您应该使用其他方法来验证请求
如果您的视图应该接受来自外部来源的 POST
,则您需要验证请求,因为每个 POST
请求都需要有一个 CSRF 令牌(参考:CSRF). Hence, for your purpose, you'll have to exempt the view from CSRF validation using @csrf_exempt
decorator and write your own validation for the request using something like Token Authentication
我编写了一个视图函数来处理 post 请求,其中包含来自 django (labview) 外部源的 json 数据。我只是在开始测试它,所以它看起来像这样
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 posts 数据 post_entry
returns 出现 403 forbidden 错误。我想这是因为没有 csrf 令牌,但为什么在这种情况下测试通过了?
测试客户端围绕 CSRF 功能工作。参见 https://docs.djangoproject.com/en/1.9/ref/csrf/#testing
如果您要有一个视图接受来自应用程序外部来源的 post 数据,您需要使用 csrf_exempt:[=12= 让您的视图免于 CSRF 保护]
@csrf_exempt
def post_entry(request):
'''Process incoming json string
'''
如果您要这样做,您应该使用其他方法来验证请求
如果您的视图应该接受来自外部来源的 POST
,则您需要验证请求,因为每个 POST
请求都需要有一个 CSRF 令牌(参考:CSRF). Hence, for your purpose, you'll have to exempt the view from CSRF validation using @csrf_exempt
decorator and write your own validation for the request using something like Token Authentication