Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

500 and 302 errors web api

500 and 302 errors web api

I'm not sure what's happening but every last request gives me 500 in my testing and every request before 500 is 302. Im using web api, python, and flask here. The code is bellow. It does provide a TypeError but I listed my code below if you can find a reason why its my fault please let me know. Lastly. I did run another python web app and it gave me all 302 errors while it had not in the past. It did not error out to 500 like this one does. 

 

 

 

 

 

CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
CLIENT_SECRET = os.getenv("SPOTIFY_CLENT_SECRET")
REDIRECT_URI = os.getenv("SPOTIFY_REDIRECT_URI")
USER_ID = os.getenv("SPOTIFY_USER_ID")


SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
MY_FOLLOWED_ARTIST_URL = "https://api.spotify.com/v1/me/following?type=artist"
MY_LIKED_SONGS = "https://api.spotify.com/v1/me/tracks?market=US&limit=15"

app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY")

formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")


def setup_logger(name, log_file, level=logging.INFO):
    # """To setup as many loggers as you want"""

    handler = logging.FileHandler(log_file)
    handler.setFormatter(formatter)

    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)

    return logger


# first file logger
logger = setup_logger("first_logger", "first_logfile.log")
# second file logger
super_logger = setup_logger("second_logger", "second_logfile.log")
error_logger = setup_logger("error_logger", "error_logfile.log")


def get_tokens():

    with open("tokens.json", "r") as outfile:
        tokens = json.load(outfile)
        logger.info("\n\ngot tokens")

    return tokens


def get_track_uris():
    with open("track_uris.json", "r") as outfile:
        track_uris = json.load(outfile)
        logger.info("\n\ngot track_uris")**bleep**("/")
def request_auth():
    scope = "user-library-read user-top-read playlist-modify-public playlist-modify-private user-follow-read user-follow-modify"
    return redirect(
        f"https://accounts.spotify.com/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={scope}"
    )**bleep**("/callback")
def request_tokens():
    # get code from spotify req param
    code = request.args.get("code")

    # necessary request body params
    payload = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI,
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
    }
    # Auth flow step 2 - request refresh and access tokens
    r = requests.post(SPOTIFY_TOKEN_URL, data=payload)
    response = r.json()  # parse json

    tokens = {
        "access_token": response["access_token"],
        "refresh_token": response["refresh_token"],
        "expires_in": response["expires_in"],
    }

    with open("tokens.json", "w") as outfile:
        json.dump(tokens, outfile)

    return redirect("/get_liked_songs")**bleep**("/get_liked_songs")
def get_liked_artists():
    tokens = hp.get_tokens()
    hp.check_expiration(tokens)

    uri = MY_LIKED_SONGS
    headers = {
        "Authorization": f'Bearer {tokens["access_token"]}',
        "Content-Type": "application/json",
    }
    r = requests.get(uri, headers=headers)
    response = r.json()
    # return response

    data = json.loads(json.dumps(response))
    track_ids = []
    finaltrue = []
    finalfalse = []
    data = json.loads(json.dumps(response))

    for item in data["items"]:
        for artist in item["track"]["album"]["artists"]:
            try:
                track_ids.append(artist["id"])
                single_ids = artist["id"]
                super_logger.info(f"testing {single_ids}")
                print(artist["id"])
                url = f"https://api.spotify.com/v1/me/following/contains?type=artist&ids={single_ids}"
                payload = {"id": single_ids}
                headers = {"Authorization": f'Bearer {tokens["access_token"]}'}
                r = requests.get(url, headers=headers, params=payload)
                response = r.json()
                super_logger.info(response)
                print(response)
                facts = response
                logger.warn(f"\n\nTrack ID response: {facts}")

                # print(r.json())
                finaltrue.append(single_ids) if True in facts else finalfalse.append(
                    single_ids
                )
                super_logger.info(f"is this the false list: {finalfalse}")
                super_logger.info(f"is this the true list: {finaltrue}")

            except Exception as e:
                # error_logger.warn(e)
                print(e)
    super_logger.info(f"is this the false list: {finalfalse}")
    super_logger.info(f"is this the true list: {finaltrue}")

    session["artist_ids"] = track_ids
    session["finalfalse2"] = finalfalse

    logger.warn(f"\n\nthis is all: {track_ids}")
    test = json.dumps(finalfalse)
    with open("i.json", "w") as outfile:
        json.dump(test, outfile)
    # for i in finalfalse:
    return  #redirect("/follow_artists")**bleep**("/follow_artists")
def follow_artists():
    tokens = hp.get_tokens()
    hp.check_expiration(tokens)
    finalfalse2 = session["finalfalse2"]
    try:
        for i in finalfalse2:
            # for line in open("i.json", "r"):
            try:
                for i in finalfalse2:
                    uri = f"https://api.spotify.com/v1/me/following?type=artist&ids={i}"
                    headers = {
                        "Authorization": f'Bearer {tokens["access_token"]}, Content-Type: "application/json"'
                    }
                    r = requests.put(uri, headers=headers)
                    response = r.status_code
                    print(f"response is:{r}")
                    print(f"liked: {response}")
                return print("\\ ALL DONE")
            except Exception as e:
                error_logger.warn(e)
                pass_e = json.load(e)
                with open("r.json", "w") as outfile:
                    json.dump(Exception, outfile)


        return print("\\ ALL DONE")

    return print("hello")


if __name__ == "__main__":
    app.run(debug=True)

 

 

 

 

 

 

Reply
0 Replies

Suggested posts

Type a product name