在ListAPIView中引发错误的请求400异常

时间:2018-11-05 16:03:03

标签: python django django-rest-framework

当用户不提供令牌或令牌无效时,我试图引发400异常,我的代码如下:

这是我的exceptions.py文件:

from rest_framework.exceptions import APIException, PermissionDenied


class MissingTokenException(APIException):
    status_code = 400
    default_detail = 'Your request does not contain token'
    default_code = 'no_token'


class InvalidTokenException(APIException):
    status_code = 400
    default_detail = 'Your request contain invalid token'
    default_code = 'invalid_token'

这是我的views.py文件:

class ListProductsOfCategory(generics.ListAPIView):
    serializer_class = ProductSerializer
    lookup_url_kwarg = 'category_id'

    def dispatch(self, *args, **kwargs):
        token = self.request.META.get("HTTP_TOKEN", "")
        if not token:
            # here I wan to raise an error saying that no token provided.
           raise MissingTokenException
        if not UserAccess.objects.filter(accessToken=token).exists():
            # here I wan to raise an error saying that token provided is not valid.
           raise InvalidTokenException
        return super().dispatch(*args, **kwargs)

    def get_queryset(self):
        category_id = self.kwargs.get(self.lookup_url_kwarg)
        return Product.objects.filter(category_id=category_id)

我正在使用邮递员测试我的API:

enter image description here

请问有没有人可以帮助django和python新手。

1 个答案:

答案 0 :(得分:1)

DRF处理most of its internals within the dispatch function,包括捕获APIException。 如果要在其外部引发#!/usr/bin/env python from flask import Flask, render_template, Response from camera import Camera app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(Camera()),mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) (这是代码的作用),则还必须捕获异常并调用异常处理程序as does DRF。 另请注意,您会错过内容协商和其他一些事情。

一种更好的处理方法是通过身份验证和权限执行检查。