Django Rest Framework 프레임워크 구현
from django.conf.urls import url, include
from web.views.s1_api import TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
from rest_framework.views import APIView
from rest_framework.response import Response
class TestView(APIView):
def dispatch(self, request, *args, **kwargs):
"""
, dispatch ,dispatch get/post/put
:APIView dispatch
"""
return super().dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return Response('GET , ')
def post(self, request, *args, **kwargs):
return Response('POST , ')
def put(self, request, *args, **kwargs):
return Response('PUT , ')
위는restframework 프레임워크의 기본 절차로 중요한 기능은 APIView의dispatch에서 터치하는 것이다.
2. 인증 및 인증
a. 사용자 URL이 전송한token 인증
from django.conf.urls import url, include
from web.viewsimport TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
view.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
from rest_framework import exceptions
token_list = [
'sfsfss123kuf3j123',
'asijnfowerkkf9812',
]
class TestAuthentication(BaseAuthentication):
def authenticate(self, request):
"""
, : ( , Token)
:param request:
:return:
None, ;
, Token
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER()
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()
else:
self.auth = None
(user,token) Token;
AuthenticationFailed
"""
val = request.query_params.get('token')
if val not in token_list:
raise exceptions.AuthenticationFailed(" ")
return (' ', ' token')
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
# , WWW-Authenticate
pass
class TestView(APIView):
authentication_classes = [TestAuthentication, ]
permission_classes = []
def get(self, request, *args, **kwargs):
print(request.user)
print(request.auth)
return Response('GET , ')
def post(self, request, *args, **kwargs):
return Response('POST , ')
def put(self, request, *args, **kwargs):
return Response('PUT , ')
b. 요청 헤더 설정
from django.conf.urls import url, include
from web.viewsimport TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
view.py
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.request import Request from rest_framework import exceptions
token_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812',
] class TestAuthentication(BaseAuthentication): def authenticate(self, request): """ , : ( , Token)
:param request:
:return:
None, ;
, Token
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER()
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()
else:
self.auth = None
(user,token) Token;
AuthenticationFailed """
import base64
auth = request.META.get('HTTP_AUTHORIZATION', b'') if auth:
auth = auth.encode('utf-8')
auth = auth.split() if not auth or auth[0].lower() != b'basic': raise exceptions.AuthenticationFailed(' ') if len(auth) != 2: raise exceptions.AuthenticationFailed(' ')
username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':') if username == 'alex' and password == '123': return (' ', ' token') else: raise exceptions.AuthenticationFailed(' ') def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses. """
return 'Basic realm=api'
class TestView(APIView):
authentication_classes = [TestAuthentication, ]
permission_classes = [] def get(self, request, *args, **kwargs): print(request.user) print(request.auth) return Response('GET , ') def post(self, request, *args, **kwargs): return Response('POST , ') def put(self, request, *args, **kwargs): return Response('PUT , ')
c. 다중 인증 규칙 url.py from django.conf.urls import url, include
from web.views.s2_auth import TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
view.py #!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
from rest_framework import exceptions
token_list = [
'sfsfss123kuf3j123',
'asijnfowerkkf9812',
]
class Test1Authentication(BaseAuthentication):
def authenticate(self, request):
"""
, : ( , Token)
:param request:
:return:
None, ;
, Token
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() # :
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()# :None
else:
self.auth = None
(user,token) Token;
AuthenticationFailed
"""
import base64
auth = request.META.get('HTTP_AUTHORIZATION', b'')
if auth:
auth = auth.encode('utf-8')
else:
return None
print(auth,'xxxx')
auth = auth.split()
if not auth or auth[0].lower() != b'basic':
raise exceptions.AuthenticationFailed(' ')
if len(auth) != 2:
raise exceptions.AuthenticationFailed(' ')
username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':')
if username == 'alex' and password == '123':
return (' ', ' token')
else:
raise exceptions.AuthenticationFailed(' ')
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
# return 'Basic realm=api'
pass
class Test2Authentication(BaseAuthentication):
def authenticate(self, request):
"""
, : ( , Token)
:param request:
:return:
None, ;
, Token
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() # :
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()# :None
else:
self.auth = None
(user,token) Token;
AuthenticationFailed
"""
val = request.query_params.get('token')
if val not in token_list:
raise exceptions.AuthenticationFailed(" ")
return (' ', ' token')
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
pass
class TestView(APIView):
authentication_classes = [Test1Authentication, Test2Authentication]
permission_classes = []
def get(self, request, *args, **kwargs):
print(request.user)
print(request.auth)
return Response('GET , ')
def post(self, request, *args, **kwargs):
return Response('POST , ')
def put(self, request, *args, **kwargs):
return Response('PUT , ')
인증 및 권한 urls.py from django.conf.urls import url, include
from web.views import TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
view.py #!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework import exceptions
token_list = [
'sfsfss123kuf3j123',
'asijnfowerkkf9812',
]
class TestAuthentication(BaseAuthentication):
def authenticate(self, request):
"""
, : ( , Token)
:param request:
:return:
None, ;
, Token
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() # :
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()# :None
else:
self.auth = None
(user,token) Token;
AuthenticationFailed
"""
val = request.query_params.get('token')
if val not in token_list:
raise exceptions.AuthenticationFailed(" ")
return (' ', ' token')
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
pass
class TestPermission(BasePermission):
message = " "
def has_permission(self, request, view):
"""
Return `True` if permission is granted, `False` otherwise.
:param request:
:param view:
:return: True ;False
"""
if request.user == " ":
return True
# GenericAPIView get_object
def has_object_permission(self, request, view, obj):
"""
GenericAPIView, get_object ,
Return `True` if permission is granted, `False` otherwise.
:param request:
:param view:
:param obj:
:return: True ;False
"""
if request.user == " ":
return True
class TestView(APIView):
# request.user
authentication_classes = [TestAuthentication, ]
#
#
permission_classes = [TestPermission, ]
def get(self, request, *args, **kwargs):
# self.dispatch
print(request.user)
print(request.auth)
return Response('GET , ')
def post(self, request, *args, **kwargs):
return Response('POST , ')
def put(self, request, *args, **kwargs):
return Response('PUT , ')
e. 글로벌 사용
위에서 설명한 작업은 개별 뷰에 대한 특수 구성이며 전역적으로 구성하려면 구성 파일에 쓰기 작업을 다시 수행해야 합니다. setting.py REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': None,
'UNAUTHENTICATED_TOKEN': None,
"DEFAULT_AUTHENTICATION_CLASSES": [
"web.utils.TestAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"web.utils.TestPermission",
],
}
urls.py from django.conf.urls import url, include
from web.views import TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
view.py #!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
class TestView(APIView):
def get(self, request, *args, **kwargs):
# self.dispatch
print(request.user)
print(request.auth)
return Response('GET , ')
def post(self, request, *args, **kwargs):
return Response('POST , ')
def put(self, request, *args, **kwargs):
return Response('PUT , ')
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.