I have been trying to emulate comment functionality with a decorator.
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)
And I used the program called Httpie to give JSON POST request like so:
http -v http://127.0.0.1:8000/comment access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJlY2sifQ.2unop67pLHOshcGs385GwOvaZZW_J--TRNXyHI3gKNU" content="hello"
There is no problem with the token since this is the exact copy of the token give during the SignInView(which is in another app).
Below is the models.py file in the 'comment' app.
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
However, when I send the POST request with the Httpie like above, I get this error:
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
I have been wondering what would cause the error. I wonder if there is no way to put the json request body into the decorator which would allow me to decode the token(the decoded version will be the username) so that I can see if it matches with the username in the database.
Thank you so much!!
I solved the problem!
def wrapper(request, *args, **kwargs):
needs to be
def wrapper(self, request, *args, **kwargs):