从邮递员运行django api:CSRF验证失败 [英] Run django api from postman: CSRF verification failed
本文介绍了从邮递员运行django api:CSRF验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试使用 postman
运行api。我的应用是使用 python 3.5
在 django 1.11.6
中开发的。
I'm trying to run an api using postman
. My application is developed in django 1.11.6
using python 3.5
.
我的应用程序安装在 ubuntu
服务器上。我没有创建 csrf
令牌的登录机制。
My app is installed on an ubuntu
server. I have no login mechanism to create a csrf
token.
这些是我遵循的步骤:
- 单击左上角的导入标签。
- 选择原始文本选项并粘贴我的
cURL
命令。 - 点击导入,我的邮递员生成器中就有该命令
- 按发送按钮。
- Click on "import" tab on the upper left side.
- Select the Raw Text option and paste my
cURL
command. - Hit import and I have the command in your Postman builder
- Press send button.
我的 curl
命令是:
curl -i -H 'Accept: application/json; indent=4' -X POST https://127.0.0.1/users/:register/ -d "id=111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames="
我得到的错误是禁止(403)-CSRF验证失败。请求中止
。
当我通过 cygwin
运行 curl命令
时,
这是我正在使用的视图函数:
This is the view function that I'm using:
class ApiUserRegister(APIView):
permission_classes = ()
serializer_class = RegisterUserSerializer
def post(self, request):
serializer = RegisterUserSerializer(data=request.data)
# Check format and unique constraint
serializer.is_valid(raise_exception=True)
data = serializer.data
if User.objects.filter(id=data['id']).exists():
user = User.objects.get(id=data['id'])
is_new = "false"
resp_status = status.HTTP_200_OK
else:
user = User.objects.create(id=data['id'],
firstname=data['firstname'],
yearofbirth=data['yearofbirth'],
lastname=data['lastname'],
othernames=data['othernames'])
user.save()
is_new = "true"
resp_status = status.HTTP_201_CREATED
resp = {"user": serializer.get_serialized(user),
"isnew": is_new}
return Response(resp, status=resp_status)
在 settings.py
中,我有:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
)
}
推荐答案
尝试一下。
from django.views.decorators.csrf import csrf_exempt
class ApiUserRegister(APIView):
permission_classes = ()
serializer_class = RegisterUserSerializer
@csrf_exempt
def post(self, request):
serializer = RegisterUserSerializer(data=request.data)
这篇关于从邮递员运行django api:CSRF验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文