私はデコレータでコメント機能をエミュレートしようとしています。
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というプログラムを使用して、次のようにJSONPOSTリクエストを送信しました。
http -v http://127.0.0.1:8000/comment access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJlY2sifQ.2unop67pLHOshcGs385GwOvaZZW_J--TRNXyHI3gKNU" content="hello"
これはSignInView(別のアプリにあります)中に提供されるトークンの正確なコピーであるため、トークンに問題はありません。
以下は、「コメント」アプリの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):
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加