(Django) 'CommentView' 对象没有属性 'body'

(Django) 'CommentView' object has no attribute 'body'

我一直在尝试用装饰器模拟评论功能。

import json
import jwt

from django.views           import View
from django.http            import JsonResponse
from functools              import wraps
from django.db.models       import Q

from .models                    import Comment
from account.models   import Account

class CommentView(View):


    def login_required(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            # import pdb; pdb.set_trace()
            given_token     = json.loads(request.body)['access_token']
            decoded_token   = jwt.decode(given_token,None,None)
            try:
                if Account.objects.filter(username=decoded_token).exists():
                    return func(request, *args, **kwargs)
                return JsonResponse({"message": "username does not exist"})
            except KeyError:
                return JsonResponse({"message": "INVALID_KEYS"}, status=403)
        return wrapper



    @login_required
    def post(self, request):
        print("request ", json.loads(request.body))
        data = json.loads(request.body)
        Comment.objects.create(
                username    = jwt.decode(json.loads(request.body)['access_token']),
                content     = data['content'],
        )
        return JsonResponse({"message":"Comment Created!"}, status=200)

    def get(self, request):
        return JsonResponse({'comment':list(Comment.objects.values())}, status=200)

然后我使用名为 Httpie 的程序来提供 JSON POST 请求,如下所示:

http -v http://127.0.0.1:8000/comment access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJlY2sifQ.2unop67pLHOshcGs385GwOvaZZW_J--TRNXyHI3gKNU" content="hello"

令牌没有问题,因为这是在 SignInView(在另一个应用程序中)期间提供的令牌的精确副本。

下面是 'comment' 应用程序中的 models.py 文件。

from django.db                  import models
from account.models   import Account

class Comment(models.Model):
    username    = models.ForeignKey(Account, on_delete=models.CASCADE)
    content     = models.TextField()
    created_time= models.DateTimeField(auto_now_add = True)
    updated_time= models.DateTimeField(auto_now = True)

    class Meta:
        db_table = 'comments'

    def __str__(self):
        return self.username + ": " + self.content

然而,当我像上面那样用 Httpie 发送 POST 请求时,我得到这个错误:

Internal Server Error: /comment
Traceback (most recent call last):
  File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/woohyunan/projects/Wecode/westagram/KillaGramz-backend/comment/views.py", line 19, in wrapper
    given_token     = json.loads(request.body)['access_token']
AttributeError: 'CommentView' object has no attribute 'body'
[20/May/2020 17:35:40] "POST /comment HTTP/1.1" 500 73224

我一直在想是什么导致了这个错误。我想知道是否没有办法将 json 请求主体放入装饰器中,这样我就可以解码令牌(解码后的版本将是用户名),以便我可以查看它是否与中的用户名匹配数据库。

非常感谢!!

我解决了问题!

def wrapper(request, *args, **kwargs):

需要

def wrapper(self, request, *args, **kwargs):