V
V
volkov12feb2022-03-18 14:52:13
JSON
volkov12feb, 2022-03-18 14:52:13

JSONDecodeError in DRF. Authorization through Spotify. How to solve the problem?

import base64
from typing import Optional

import requests
from django.conf import settings
from rest_framework.exceptions import AuthenticationFailed


def get_spotify_jwt(code: str) -> Optional[str]:
    url = 'https://accounts.cpotify.com/api/token'
    basic_str = f'{settings.SPOTIFY_CLIENT_ID}:{settings.SPOTIFY_SECRET}'.encode('ascii')
    basic = base64.b64encode(basic_str)
    data = {
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': 'http://localhost:8000/spotify-callback'
    }
    headers = {
        'Authorization': f'Basic {basic.decode("ascii")}'
    }
    res = requests.post(url, data=data)
    if res.status_code == 200:
        r = res.json()
        return r.get('access_token')
    else:
        return None

def spotify_auth(code: str):
    _token = get_spotify_jwt(code)
    if _token is not None:
        url_get_user = 'https://api.spotify.com/v1/me'
        headers = {'Authorization': f'Bearer{_token}'}
        res = requests.get(url_get_user, headers=headers)
        r = res.json()
        print(r.get('email'))
    else:
        raise AuthenticationFailed(code=403, detail='Bad token Spotify')


6234724d229c3770501080.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-03-18
@bacon

because you received not json, but html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question