其他分享
首页 > 其他分享> > Django REST framework之BasicAuthentication

Django REST framework之BasicAuthentication

作者:互联网

目的

一直用Token做Django REST API的验证方式,突然有个低安全要求的应用,只用用户名密码来访问。

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'user': str(request.user),  # `django.contrib.auth.User` instance.
            'auth': str(request.auth),  # None
        }
        return Response(content)

实现方式一 

python 的requests的

url="http://127.0.0.1:8000/customs_app/customs_special_material_clearance/"
res=requests.get(url=url,auth=HTTPBasicAuth(username="username",password="password"))
print(res.text)

实现方式二 

根据HTTPBasicAuth 自己设置headers

import base64
headers={}
headers["Authorization"]='Basic ' +   base64.b64encode(b':'.join(("username".encode(), "password".encode()))).decode()
url="http://127.0.0.1:8000/customs_app/customs_special_material_clearance/"
res=requests.get(url=url,headers=headers)
print(res.text)

 

标签:headers,url,res,REST,framework,rest,import,BasicAuthentication
来源: https://www.cnblogs.com/Evan-fanfan/p/BasicAuthentication.html