I am using the spotipy library to add songs to a playlists but I keep getting errors when trying to use the 'playlist-modify-private' scope. When trying to gain authorization, the web browser opens and I allow the app access to my spotify accoutn and then i'm immediately met with an error screen. Rerunning the app just brings me straight to the error screen. I get no error code or anything so I'm lost as to why this is happening.
self.scope = 'playlist-modify-private'
self.redirect_uri = 'localhost:8888/callback'
self.auth = util.prompt_for_user_token(username=self.username,
scope=self.scope,
client_id=self.client_id,
client_secret=self.client_secret,
redirect_uri=self.redirect_uri)
I saw a post saying that for this scope i should be using util module for auth but i've had no luck. Originally I was using the auth SpotifyClientCredentials object and was able to finish most of the project but I was unable to modify playlist since it doesn't take a scope. I'm at a loss if anyone can provide any input.
Try this:
First set the following environment variables on your env.
SPOTIPY_CLIENT_ID="<your_client_id>"
SPOTIPY_CLIENT_SECRET="<your_client_secret>"
SPOTIPY_REDIRECT_URI="http://127.0.0.1:8888/callback"
SPOTIPY_CLIENT_USERNAME="<your_username>"
And then run the following (I'm using dotenv to load the variables above) Check out the doc here:
import os
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from dotenv import load_dotenv
load_dotenv() # Load your environment variables from a .env file
spotify_user = os.environ.get("SPOTIPY_CLIENT_USERNAME")
spotify_scope = "playlist-modify-private"
oauth = SpotifyOAuth(username=spotify_user, scope=spotify_scope)
user_token = oauth.get_access_token(as_dict=False)
That will take you to your redirect_uri and generate a .cache-<your_username> file with all the information needed (token, refresh_token, etc.)
Then you create your spotify client with:
spotify = spotipy.Spotify(auth=user_token)
This will automatically get your token or get a refresh token in case it's needed so you won't have to worry about this.
And then you will be able to modify your playlist with:
spotify.user_playlist_add_tracks(
user=os.environ.get("SPOTIPY_CLIENT_USERNAME"),
playlist_id="<your_playlist_uri>",
tracks=["<track_uri>"])
Here's the doc reference for the environment variables used by the spotipy library: https://spotipy.readthedocs.io/en/2.15.0/?highlight=environment%20variables#quick-start
Related
How to create a container of cloud run by python library like from google.cloud import run_v2,
I am not getting any example for creating container with by python code
Well, first you need to create a service account and credentials here https://console.cloud.google.com/apis/credentials?project=
Next, you need to either download the key or use any other authentication method, in my example, the key.
# init credentials
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file("prject-key.json")
# create client
import google.cloud.run_v2 as run_v2
run_client = run_v2.ServicesClient(credentials=credentials)
# build request
from google.cloud.run_v2 import ListServicesRequest
request = ListServicesRequest(
parent="projects/{projectnumber}/locations/{location}"
)
# response
response = run_client.list_services(request=request)
Here you can find samples: https://github.com/googleapis/python-run/tree/main/samples/generated_samples
Also keep in mind that permissions work depending on the authentication method. Somewhere the IP whitelist is indicated somewhere not
I attempted to run the code below and am getting an error that states:
HTTP Error code: 403: Forbidden: Authentication succeeded but account is not authorized to access this resource.
from searchtweets import ResultStream, gen_rule_payload, load_credentials, collect_results
import requests
premium_search_args = load_credentials("/home/dirname/twitter_keys.yaml",
yaml_key="search_tweets_premium",
env_overwrite=False)
rule = gen_rule_payload("basketball", results_per_call=100) # testing with a sandbox account
print(rule)
from searchtweets import collect_results
tweets = collect_results(rule,
max_results=100,
result_stream_args=premium_search_args)
# print(tweets.all_text)
[print(tweet.all_text, end='\n\n') for tweet in tweets[0:10]];
My YAML file looks like this:
search_tweets_premium:
account_type: premium
endpoint: https://api.twitter.com/1.1/tweets/search/fullarchive/dev.json
consumer_key: AAAAAAAAAAAAAAAAAAAAA
consumer_secret: BBBBBBBBBBBBBBBBBBBBBBBBBBB
Only other thing to note is that I am using the free/sandbox service.
Any ideas if I am doing anything wrong in the code, the YAML, and/or within my Twitter developer account?
You'll need to go to https://developer.twitter.com/en/account/environments
There you should be able to see the various development environments that you have. You can create one should they not have been created.
The dev environment label would then be the thing you use to replace in your endpoint.
In my example, it would be:
https://api.twitter.com/1.1/tweets/search/fullarchive/development.json
If that still doesn't work, you might need to include a bearer token in your YAML file.
First of all, I'm not a Python guru as you can probably tell... So here we go.
I'm trying to use Asana's API to pull data with Python requests (Projects, tasks, etc) and doing the authentication using Oauth 2.0... I've been trying to find a simple python script to have something to begin with but I haven't had any luck and I can't find a decent and simple example!
I already created the app and got my client_secret and client_secret. But I don't really know where or how to start... Could anybody help me please?
import sys, os, requests
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import asana
import json
from six import print_
import requests_oauthlib
from requests_oauthlib import OAuth2Session
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
if 'ASANA_CLIENT_ID' in os.environ:
#Creates a client with previously obtained Oauth credentials#
client = asana.Client.oauth(
#Asana Client ID and Secret, set as a Windows environments to avoid hardcoding variables into the script#
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
print ("authorized=", client.session.authorized)
# get an authorization URL:
(url, state) = client.session.authorization_url()
try:
# in a web app you'd redirect the user to this URL when they take action to
# login with Asana or connect their account to Asana
import webbrowser
webbrowser.open(url)
except Exception as e:
print_("Open the following URL in a browser to authorize:")
print_(url)
print_("Copy and paste the returned code from the browser and press enter:")
code = sys.stdin.readline().strip()
# exchange the code for a bearer token
token = client.session.fetch_token(code=code)
#print_("token=", json.dumps(token))
print_("authorized=", client.session.authorized)
me = client.users.me()
print "Hello " + me['name'] + "\n"
params = {'client_id' : client_id, 'redirect_uri' : redirect_uri, 'response_type' : token,}
print_("*************** Request begings *******************"+"\n")
print_("r = requests.get('https://app.asana.com/api/1.0/users/me)" + "\n")
r = requests.get('https://app.asana.com/api/1.0/users/me', params)
print_(r)
print_(r.json)
print_(r.encoding)
workspace_id = me['workspaces'][0]['id']
print_("My workspace ID is" + "\n")
print_(workspace_id)
print_(client.options)
I'm not sure how to use the requests lib with Asana. Their python doc did not help me. I'm trying to pull the available projects and their code colours so I can later plot them into a web browser (For a high-level view of the different projects and their respective colours - Green, yellow or red)
When I introduce the url (https://app.asana.com/api/1.0/users/me) into a browser, it gives me back a json response with the data, but when I try to do the same with the script, it gives me back a 401 (not authorized) response.
Does anybody know what I'm missing / doing wrong?
Thank you!!!
I believe the issue is that the Requests library is a lower level library. You would need to pass all of the parameters to your requests.
Is there a reason you are not exclusively using the Asana Python client library to make requests? All of the data you are looking to fetch from Asana (projects, tasks, etc.) are accessible using the Asana Python library. You will want to look in the library to find the methods you need. For example, the methods for the tasks resource can be found here. I think this approach will be easier (and less error-prone) than switching between the Asana lib and the Requests lib. The Asana lib is actually built on top of Requests (as seen here).
Anyone know if this is possible?
I just want to automate dropping some documents into my onedrive for business account.
I tried
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest
redirect_uri = 'http://localhost:8080'
client_id = 'appid'
client_secret = 'mysecret'
discovery_uri = 'https://api.office.com/discovery/'
auth_server_url='https://login.live.com/oauth20_authorize.srf?scope=wl.skydrive_update'
#auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize',
auth_token_url='https://login.microsoftonline.com/common/oauth2/token'
http = onedrivesdk.HttpProvider()
auth = onedrivesdk.AuthProvider(http,
client_id,
auth_server_url=auth_server_url,
auth_token_url=auth_token_url)
auth_url = auth.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
auth.authenticate(code, redirect_uri, client_secret, resource=resource)
# If you have access to more than one service, you'll need to decide
# which ServiceInfo to use instead of just using the first one, as below.
service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)[0]
auth.redeem_refresh_token(service_info.service_resource_id)
client = onedrivesdk.OneDriveClient(service_info.service_resource_id + '/_api/v2.0/', auth, http)
I registered an APP and got a secret and id. But when I ran this I got scope is invalid errors. Plus it tries to launch a webpage which isn't great for a command line kinda environment. I think this SDK might be outdated as well because originally this script had login.microsoftonline, but that wasn't reachable so I changed it to login.live.com.
I wrote this sample code you posted. You replaced the auth_server_URLwith the authentication URL for Microsoft Account authentication, which can only be used to access OneDrive (the consumer product). You need to continue using the login.microsoftonline.com URL to log into your OneDrive for Business account.
You are correct that this pops up a dialog. However, you can write a little supporting code so that only happens the first time you log into a particular app. Follow these steps (assuming you are using the default implementation of AuthProvider:
Use the sample code above up through the line auth.redeem_refresh_token()
The AuthProvider will now have a Session object, which caches the credentials of the current user and session. Use AuthProvider.save_session() to save the credentials for later.
Next time you start your app, use AuthProvider.load_session() and AuthProvider.refresh_token() to retrieve the previous session and refresh the auth token. This will all be headless.
Take note that the default implementation of SessionBase (found here) uses Pickle and is not safe for product use. Make sure to create a new implementation of Session if you intend to deploy this app to other users.
Onerive's website shows "Not Yet" on "OneDrive SDK for Python" to "OneDrive for Business"
https://dev.onedrive.com/SDKs.htm
The github sample codes did not work for me either, it tried to popup a window of authentication, but IE can not find the address:
http://('https//login.microsoftonline.com/common/oauth2/authorize',)?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=034xxxx9-9xx8-4xxf-bexx-1bc5xxxxbd0c&response_type=code
or removed all the "-" in client id
http://('https//login.microsoftonline.com/common/oauth2/authorize',)?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=034xxxx99xx84xxfbexx1bc5xxxxbd0c&response_type=code
Either way, I got the same result, IE did not show the popup with a line "This page can’t be displayed"
I had a Python script that I had authorized to access a Google Spreadsheet. But when now when I run it, it throws the exception:
oauth2client.client.AccessTokenRefreshError: invalid_client: The OAuth client was not found.
My auth code looks like:
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
json_key = json.load(open('myapp-credentials.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(
json_key['client_email'],
json_key['private_key'], scope)
gc = gspread.authorize(credentials)
I've not changed anything in the account, so I don't know why it would suddenly stop working. If I login to https://console.developers.google.com/apis/credentials, I see the app is still registered. How do I diagnose this and re-enable its access? Googling this error unfortunately finds dozens of potential causes.
The class SignedJwtAssertionCredentials has been removed from the source code as of February 5, 2016, and its functionality replaced with that of ServiceAccountCredentials. This may be causing your error.
It appears that you'll want to use something like the following to generate your credentials:
credentials = ServiceAccountCredentials.from_json_keyfile_name('myapp-credentials.json', scope)
This Github issue thread might be helpful, as well.