I'm starting to code a project based on the spotify API in Python, using the Spotipy module. This is my code
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import requests as rq
SPOTIPY_CLIENT_ID="..."
SPOTIPY_CLIENT_SECRET="..."
SPOTIPY_REDIRECT_URI="http://127.0.0.1:9090"
SCOPE = "playlist-read-private%20user-read-email"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=SPOTIPY_REDIRECT_URI, scope=SCOPE))
user_playlists = sp.current_user_playlists()
for i in user_playlists["items"]:
print(i["name"])
So this code requires a user to grant permission to the app to see its playlists. The problem I'm having is that once I login with an account and grant permission, I can't find any way to change the user. Any clue how to do so? Thanks in advance
When you execute this code you will find that a new cache file will be created wherever the file of your code is. The filename would be something like ".cache-'username' ". This cache file contains the access token you get. If you want to change the account, the simplest way would be deleting the file and re-running the code and logging with the different user account.
Note - You have to be careful to login with the same account which you mention in the code otherwise the access token would be of no use.
Hope you find this useful.
Related
I am building a local desktop app where I can read, classify, and create playlists.
The following auth code I have is:
##oauth
scope = "playlist-modify-public playlist-read-private playlist-modify-private"
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri= "https://example.com/callback/",
scope= scope, open_browser=False))
when run on cmd, this asks to click the link generated and then to paste the link that I was redirected to. I want to know if there is another way to provide authorization (automatically or permanently) so that my .exe app doesn't run into an error.
code in your response would help a lot.
You cannot grant permanent access to the APIs in a single call, but you can refresh your token automatically whenever the access expires, as shown in the docs.
If you're using Python, I recommend to do this via Spotipy, which makes the auth process much easier (see https://spotipy.readthedocs.io/en/master/#authorization-code-flow)
My goal is to create a python script, that connects to a Minecraft server.
Apparently barneygale/quarry is a widely used library for this purpose.
My problem right now is, that I cant't find a way to use this library with an Microsoft Account. The Profile.from_credentials function apparently only works with Mojang accounts.
There is an other way to create a profile, using an access token and a client token.
I've found another library (msmcauth), which creates a new access token, but I can't figure out, were to get the client token.
Here is my code:
from quarry.net.auth import Profile
import msmcauth
loginDetails = msmcauth.login("email", "password")
profile = Profile.from_token("foo", loginDetails.access_token, loginDetails.uuid, loginDetails.username)
I think you should change the place of the arguments.
the order is:
profile = Profile.from_token("foo", loginDetails.access_token, loginDetails.username, loginDetails.uuid)
It works for me...
I'm currently attempting to use spotipy, a python3 module, to access and edit my personal Spotify premium account. I've followed the tutorial on https://github.com/plamere/spotipy/blob/master/docs/index.rst using the util.prompt_for_user_token method by entering the necessary parameters directly (username, client ID, secret ID, scope and redirect uri). Everything seems to be fine up to this part. My code (fillers for username, client id and client secret for security reasons) :
code
It opens up my default web browser and redirects me to my redirect url with the code in it. At this point, I copy and paste the redirect url (as prompted) and hit enter. It returns the following error:
Error
My redirect uri is 'http://google.com/' for this specific example. However, I've tried multiple redirect uris but they all seem to produce the same error for me. (and yes, I did set my redirect uri as whitespace for my application). I've spent hours trying to fix this issue by looking at online tutorials, trying different redirect urls, changing my code but have yet to make any progress. I'm hoping I am just overlooking a simple mistake here! Any feedback on how to fix this is much appreciated!
If it matters: I'm using the IDE PyCharm.
I had to use two different solutions to deal with the redirect_uri issue depending on which IDE I was using. For Jupyter Lab/Notebook, I could use a localhost for the redirect_url
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="your_client_id", client_secret="your_client_secret", redirect_uri="https://localhost:8890/callback/", scope="user-library-read"))
For Google Colab, I had to use a publicly accessible website. I think "https://google.com/" should work but I used my band's website so I'd remember that the redirect_uri had to match the one in your Spotify Develop dashboard settings.
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="your_client_id", client_secret="your_client_secret", redirect_uri="https://yourwebsite.com/", scope="user-library-read"))
I just ended up using my bands website because it was easier for me to remember. Make sure to go to the Spotify developer dashboard (https://developer.spotify.com/dashboard/applications) and match the redirect_uri with what you are planning to use at that time.
I think it is your redirect URL - working for me with:
import os
import spotipy.util as util
# credentials
user = 'username'
desired_scope = 'playlist-modify-private'
id = os.environ.get('SPOT_CLIENT')
secret = os.environ.get('SPOT_SECRET')
uri = 'https://localhost'
token = util.prompt_for_user_token(username=user,
scope=desired_scope,
client_id=id,
client_secret=secret,
redirect_uri=uri)
I think for your redirect url spotify requires the initial http(s) part - don't forget to add it to the white-list in your Spotify for Developers app too, as otherwise you will get 'invalid-redirect-uri'.
I have code below that was given to me to list Google Cloud Service Accounts for a specific Project.
import os
from googleapiclient import discovery
from gcp import get_key
"""gets all Service Accounts from the Service Account page"""
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()
service = discovery.build('iam', 'v1')
project_id = 'projects/<google cloud project>'
request = service.projects().serviceAccounts().list(name=project_id)
response = request.execute()
accounts = response['accounts']
for account in accounts:
print(account['email'])
This code works perfectly and prints the accounts as I need them. What I'm trying to figure out is:
Where can I go to see how to construct code like this? I found a site that has references to the Python API Client, but I can't seem to figure out how to make the code above from it. I can see the Method to list the Service Accounts, but it's still not giving me enough information.
Is there somewhere else I should be going to educate myself. Any information you have is appreciated so I don't pull out the rest of my hair.
Thanks, Eric
Let me share with you this documentation page, where there is a detailed explanation on how to build a script such as the one you shared, and what does each line of code mean. It is extracted from the documentation of ML Engine, not IAM, but it is using the same Python Google API Client Libary, so just ignore the references to ML and the rest will be useful for you.
In any case, here it is a commented version of your code, so that you understand it better:
# Imports for the Client API Libraries and the key management
import os
from googleapiclient import discovery
from gcp import get_key
# Look for an environment variable containing the credentials for Google Cloud Platform
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()
# Build a Python representation of the REST API
service = discovery.build('iam', 'v1')
# Define the Project ID of your project
project_id = 'projects/<google cloud project>'
"""Until this point, the code is general to any API
From this point on, it is specific to the IAM API"""
# Create the request using the appropriate 'serviceAccounts' API
# You can substitute serviceAccounts by any other available API
request = service.projects().serviceAccounts().list(name=project_id)
# Execute the request that was built in the previous step
response = request.execute()
# Process the data from the response obtained with the request execution
accounts = response['accounts']
for account in accounts:
print(account['email'])
Once you understand the first part of the code, the last lines are specific to the API you are using, which in this case is the Google IAM API. In this link, you can find detailed information on the methods available and what they do.
Then, you can follow the Python API Client Library documentation that you shared in order to see how to call the methods. For instance, in the code you shared, the method used depends on service, which is the Python representation of the API, and then goes down the tree of methods in the last link as in projects(), then serviceAccounts() and finally the specificlist() method, which ends up in request = service.projects().serviceAccounts().list(name=project_id).
Finally, just in case you are interested in the other available APIs, please refer to this page for more information.
I hope the comments I made on your code were of help, and that the documentation shared makes it easier for you to understand how a code like that one could be scripted.
You can use ipython having googleapiclient installed - with something like:
sudo pip install --upgrade google-api-python-client
You can go to interactive python console and do:
from googleapiclient import discovery
dir(discovery)
help(discovery)
dir - gives all entries that object has - so:
a = ''
dir(a)
Will tell what you can do with string object. Doing help(a) will give help for string object. You can do dipper:
dir(discovery)
# and then for instance
help(discovery.re)
You can call your script in steps, and see what is result print it, do some research, having something - do %history to printout your session, and have solution that can be triggered as a script.
I'm trying to open a file that needs an authorization token for the request, using the cloudstorage api.
Using a token previously defined: 'access_token', my code looks like this:
gcs_file = gcs.open(file_path, 'w', options={'Authorization': access_token})
The problem is that I'm getting the following error:
option Authorization is not supported
I guess that I'm not opening this file properly.
Does someone know how should I invoke this function with the token?
Thanks a lot!
You can access buckets and objects that don't belong to your project, so long as your app's service account has been granted access. If you have literally been handed a valid OAuth 2 access token and want to use that, you could use the Google API Python Client, which can use the oauth2client.client.AccessTokenCredentials class to authenticate with an access token.
I'm curious, though. Where did your app get ahold of an access token and why do you want to use it?