Django REST_framework Quickstart

局部避免crsf的方式

针对视图函数:

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt 
def foo(request):
    return HttpResponse("foo")

针对CBV:

# 方式1  在类上方使用
@method_decorator(csrf_exempt,name="dispatch")
class IndexView(View):
    # 方式2  在类的 dispatch 方法上使用 @csrf_exempt
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
    print("hello world")
    # 执行父类的dispatch方法                        
        res=super(IndexView,self).dispatch(request, *args, **kwargs)
        print("hello boy")
        return res          
                    

在url中配置:

from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),
]

 rest_framework的简单示例

 

以books为例:

(1)创建表,数据迁移
(2)创建表序列化类BookSerializer
class BookSerializer(serializers.HyperlinkedModelSerializer):
	class Meta:
		model=Book
		fields="__all__"
 
(3)创建视图类:
  class BookViewSet(viewsets.ModelViewSet):
		queryset = Book.objects.all()
		serializer_class = BookSerializer

(4) 设计url:
 router.register(r'books', views.BookViewSet)

APIview

from rest_framework.views import APIView

class APIView(View):    
    def as_view():     
        view = super(APIView, cls).as_view(**initkwargs)  #  self.dispatch
        
    def dispatch():
         # 重新封装request
         request = self.initialize_request(request, *args, **kwargs)
         self.request = request
         
        # 初始化操作
        self.initial(request, *args, **kwargs)
            
        if request.method.lower() in self.http_method_names: 
       # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] handler = getattr(self, request.method.lower(),self.http_method_not_allowed)
       # handler=self.get response = handler(request, *args, **kwargs) # self.get(request, *args, **kwargs) 1 CBV : as_view dispatch 2 掌握API源码流程: as_view dispatch 3 serializers组件

 

转载于:https://www.cnblogs.com/iyouyue/p/8746942.html

### 实现JWT认证 为了实现JSON Web Token (JWT) 认证,在`settings.py`文件中需向Django REST框架的默认认证类列表添加`JSONWebTokenAuthentication`[^1]。 配置如下所示: ```python REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } ``` 安装必要的包对于集成JWT至关重要。通过pip可以轻松完成DRF及其JWT支持库的安装[^4]。 ```bash python -m pip install djangorestframework python -m pip install djangorestframework-jwt ``` 当请求到达时,`request.user`属性会返回由当前请求的身份验证类所确认的相关用户对象[^3]。此过程涉及调用内部方法来处理实际的身份验证逻辑并设置用户实例。 创建视图函数或类时,可以通过装饰器或者基于类的方法限制访问权限,仅允许经过适当授权的用户继续操作。例如: ```python from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): content = {'message': 'Hello, you are authenticated!'} return Response(content) ``` 上述代码片段展示了如何定义一个简单的API端点,并确保只有已登录且有效令牌存在的客户端才能成功发起GET请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值