Go教程

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)

 

这篇关于Django REST framework之BasicAuthentication的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!