Really confused because this functionality was working a few days ago and I made no substantial changes to my code.
I am getting this traceback:
Traceback (most recent call last):
File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
File "C:\Users\15512\anaconda3\lib\site-packages\django\core\serializers\json.py", line 105, in default
return super().default(o)
File "C:\Users\15512\anaconda3\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
To summarize, I am sending a name to the Twilio library with the expectation of receiving a JWT_token. The API endpoint would then return a dict with a key: title and jwt_token
This is what my view for the end point looks like:
class TokenView(View):
def get(self, request, username, *args, **kwargs):
voice_grant = grants.VoiceGrant(
outgoing_application_sid=settings.TWIML_APPLICATION_SID,
incoming_allow=True,
)
access_token = AccessToken(
settings.TWILIO_ACCOUNT_SID,
settings.TWILIO_API_KEY,
settings.TWILIO_API_SECRET,
identity=username
)
access_token.add_grant(voice_grant)
jwt_token = access_token.to_jwt()
full_data = {'token': jwt_token}
# print(type(jwt_token))
return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False)
I've also tried to have this in the return statement:
JsonResponse({"token": jwt_token})
CodePudding user response:
access_token.to_jwt()
returns a byte
, simply decode the token: access_token.to_jwt().decode()
Full code:
class TokenView(View):
def get(self, request, username, *args, **kwargs):
voice_grant = grants.VoiceGrant(
outgoing_application_sid=settings.TWIML_APPLICATION_SID,
incoming_allow=True,
)
access_token = AccessToken(
settings.TWILIO_ACCOUNT_SID,
settings.TWILIO_API_KEY,
settings.TWILIO_API_SECRET,
identity=username
)
access_token.add_grant(voice_grant)
jwt_token = access_token.to_jwt()
full_data = {'token': jwt_token.decode()}
# print(type(jwt_token))
return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False)
That should work.