[GH-ISSUE #12] How to handle cookies / sessions #9

Closed
opened 2026-02-27 19:06:25 +03:00 by kerem · 1 comment
Owner

Originally created by @shillshocked on GitHub (Jan 18, 2025).
Original GitHub issue: https://github.com/Aran404/SpotAPI/issues/12

I tried this:

import logging
import json
from spotapi.client import TLSClient
from spotapi.artist import Artist
from spotapi.login import Login

# Set up a simple logger
class BasicLogger:
    def __init__(self):
        self.logger = logging.getLogger("BasicLogger")
        self.logger.setLevel(logging.DEBUG)
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

def load_cookies_from_json(cookies_path):
    try:
        with open(cookies_path, 'r') as cookie_file:
            cookies = json.load(cookie_file)
        return cookies
    except Exception as e:
        print(f"Error loading cookies: {e}")
        return None

def get_artist_info(uri, cookies_path):
    try:
        logger = BasicLogger()
        cookies = load_cookies_from_json(cookies_path)

        if cookies is None:
            logger.error("No cookies found.")
            return

        # Use cookies with Login class to create a session
        login = Login(cookies=cookies)
        if not login.logged_in:
            logger.error("Failed to log in with cookies.")
            return

        # Initialize TLSClient with the login session
        client = TLSClient("chrome_120", login=login)

        # Create the Artist object
        artist_info = Artist(uri, client=client)

        # Use 'paginate_artists' to fetch artist data
        artist_data = artist_info.paginate_artists(uri)

        if not artist_data:
            logger.warning(f"No data found for artist URI: {uri}")
        else:
            for item in artist_data:
                print(item)

    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage
if __name__ == "__main__":
    artist_uri = "spotify:artist:0LHG14z6WbWvKtUNTMF7Ww"  # Replace with the artist URI you're testing
    cookies_path = "cookies.json"  # Update with the actual path to your cookies JSON file

    get_artist_info(artist_uri, cookies_path)

I get this:
PS C:\Scripts\newtest2\test> python -u C://Scripts//windows//testspot7.py
An error occurred: Login.init() got an unexpected keyword argument 'cookies'
PS C:\Scripts\newtest2\test>

Cookies in cookies.json are correct. What am I doing wrong here?

I tried the other method described, but it didn't have explicit code instructions, and I couldn't get it to work.

Originally created by @shillshocked on GitHub (Jan 18, 2025). Original GitHub issue: https://github.com/Aran404/SpotAPI/issues/12 I tried this: ``` import logging import json from spotapi.client import TLSClient from spotapi.artist import Artist from spotapi.login import Login # Set up a simple logger class BasicLogger: def __init__(self): self.logger = logging.getLogger("BasicLogger") self.logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) self.logger.addHandler(console_handler) def info(self, msg): self.logger.info(msg) def warning(self, msg): self.logger.warning(msg) def error(self, msg): self.logger.error(msg) def load_cookies_from_json(cookies_path): try: with open(cookies_path, 'r') as cookie_file: cookies = json.load(cookie_file) return cookies except Exception as e: print(f"Error loading cookies: {e}") return None def get_artist_info(uri, cookies_path): try: logger = BasicLogger() cookies = load_cookies_from_json(cookies_path) if cookies is None: logger.error("No cookies found.") return # Use cookies with Login class to create a session login = Login(cookies=cookies) if not login.logged_in: logger.error("Failed to log in with cookies.") return # Initialize TLSClient with the login session client = TLSClient("chrome_120", login=login) # Create the Artist object artist_info = Artist(uri, client=client) # Use 'paginate_artists' to fetch artist data artist_data = artist_info.paginate_artists(uri) if not artist_data: logger.warning(f"No data found for artist URI: {uri}") else: for item in artist_data: print(item) except Exception as e: print(f"An error occurred: {e}") # Example usage if __name__ == "__main__": artist_uri = "spotify:artist:0LHG14z6WbWvKtUNTMF7Ww" # Replace with the artist URI you're testing cookies_path = "cookies.json" # Update with the actual path to your cookies JSON file get_artist_info(artist_uri, cookies_path) ``` I get this: PS C:\Scripts\newtest2\test> python -u C://Scripts//windows//testspot7.py An error occurred: Login.__init__() got an unexpected keyword argument 'cookies' PS C:\Scripts\newtest2\test> Cookies in cookies.json are correct. What am I doing wrong here? I tried the other method described, but it didn't have explicit code instructions, and I couldn't get it to work.
kerem closed this issue 2026-02-27 19:06:25 +03:00
Author
Owner

@shillshocked commented on GitHub (Jan 18, 2025):

Ah... figured it out:

import json
from spotapi import Login, Config, Logger

# Load cookies from file
cookies = {
    'sp_dc': '<cookie string>',
    'sp_key': '<cookie string>'
}

# Manually create the session data in the correct format
session_data = {
    'identifier': 'your_session_identifier',  # Replace with your session identifier
    'cookies': cookies
}

print("Loaded session data:", session_data)

# Initialize configuration
cfg = Config(logger=Logger())

try:
    # Initialize login using the correct session data format
    login = Login.from_cookies(session_data, cfg)

    if login.logged_in:

        print(f"Successfully logged in as {login}")
    else:
        print("Login failed. Could not authenticate.")
except ValueError as e:
    print(f"Error during login: {e}")

<!-- gh-comment-id:2599601427 --> @shillshocked commented on GitHub (Jan 18, 2025): Ah... figured it out: ``` import json from spotapi import Login, Config, Logger # Load cookies from file cookies = { 'sp_dc': '<cookie string>', 'sp_key': '<cookie string>' } # Manually create the session data in the correct format session_data = { 'identifier': 'your_session_identifier', # Replace with your session identifier 'cookies': cookies } print("Loaded session data:", session_data) # Initialize configuration cfg = Config(logger=Logger()) try: # Initialize login using the correct session data format login = Login.from_cookies(session_data, cfg) if login.logged_in: print(f"Successfully logged in as {login}") else: print("Login failed. Could not authenticate.") except ValueError as e: print(f"Error during login: {e}") ```
Sign in to join this conversation.
No labels
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/SpotAPI#9
No description provided.