Spotipy Token Caching with Django - python

I am trying to host an app which utilizes the Spotipy library to create and add songs to user's Spotify accounts. The app works fine on my local as the authorization token is stored in the root folder and when prompted on my terminal I am able to "Enter the URL you were redirected to:". I'm using Pythonanywhere to host the app and can see in the server log that the same question is asked but obviously Ito no answer. I've been reading about Django Sessions to try and cache user's tokens but am a bit lost and the only example in the documentation is for Flask.
The code I am using is below - happy to share more from additional files if needed, any help is greatly appreciated!
The function that creates a new playlist and adds songs to it is triggered when a form is submitted which contains the user's Spotify Username and the 'group' object which is later used to name the playlist...
def AggregateTopsList(group, queryset, spotify_user_id, song_limit, start_date, end_date):
2. imports...
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from spotipy.oauth2 import SpotifyClientCredentials
import pandas as pd
3. Spotify API Authentication - client credentials (redirect URI, client ID & client secret) are stored as environment variables. I assume this is where I'll need to implement something to cache users tokens…
scope="playlist-modify-public"
spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
<code to determine which songs to add to the playlist, which creates a list of track IDs in a variable called 'songs'>
4. Using the Spotipy library to - create a new playlist, determine the ID of that new playlist and add songs to it. Assume this is when my terminal prompts me to enter the redirect URL that pops up
'''create new playlist'''
createnewplaylist = sp.user_playlist_create(spotify_user_id, group.name, public=True, collaborative=False, description='test')
'''determine ID of newly created playlist'''
newplaylistinfo = sp.user_playlists(spotify_user_id)
playlist_id = newplaylistinfo['items'][0]['id']
'''add 'songs' to new playlist'''
add_tracks = sp.playlist_add_items(playlist_id, songs, position=None)
Here is the error within Pythonanywhere:
2022-10-18 00:58:37,526: User authentication requires interaction with your web browser. Once you enter your credentials and give authorization, you will be redirected to a url. Paste that url you were directed to to complete the authorization. 2022-10-18 00:58:37,626: Opened https://accounts.spotify.com/authorize?client_id=ef35ce3c64be47769869fa2cb401798e&response_type=code&redirect_uri=http%3A%2F%2Ftopsnight.pythonanywhere.com%2F&scope=playlist-modify-public in your browser 2022-10-18 00:58:38,123: Internal Server Error: /TopsList/Group/11/aggregate Traceback (most recent call last): File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/oauth2.py", line 115, in _get_user_input return raw_input(prompt) NameError: name 'raw_input' is not defined NO MATCH During handling of the above exception, another exception occurred: NO MATCH Traceback (most recent call last): File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/topsnight/topsnight/./TopsListGenerator/views.py", line 238, in aggregategroup topslist = AggregateTopsList(agggroup, aggplaylists, song_limit, spotify_user_id, start_date, end_date) File "/home/topsnight/topsnight/./TopsListGenerator/functions.py", line 104, in AggregateTopsList createnewplaylist = sp.user_playlist_create(spotify_user_id, group.name, public=True, collaborative=False, description='test') File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/client.py", line 784, in user_playlist_create return self._post("users/%s/playlists" % (user,), payload=data) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/client.py", line 302, in _post return self._internal_call("POST", url, payload, kwargs) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/client.py", line 221, in _internal_call headers = self._auth_headers() File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/client.py", line 212, in _auth_headers token = self.auth_manager.get_access_token(as_dict=False) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/oauth2.py", line 535, in get_access_token "code": code or self.get_auth_response(), File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/oauth2.py", line 499, in get_auth_response return self._get_auth_response_interactive(open_browser=open_browser) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/oauth2.py", line 450, in _get_auth_response_interactive response = self._get_user_input(prompt) File "/home/topsnight/.virtualenvs/topsnightenv/lib/python3.9/site-packages/spotipy/oauth2.py", line 117, in _get_user_input return input(prompt) EOFError: EOF when reading a line

Related

google.auth.exceptions.RefresError: 'No access token in response.'

Environment details
OS type and version:
Python version: 3.9.0
pip version: 22.0.4
google-api-python-client version: 2.48.0
Description
Hi, I'm running into an error when trying to fetch the Google Play Console reports of our mobile apps (such as installations, errors etc.). I first tried with this manual but it seems to be outdated and didn't work. So after some research I changed it similar to this one, that it fits to the current google api (see code snippet below).
Steps I have done:
Created a project on "console.cloud.google.com"
Created the service account
Created the json key file
Invited the service account on play.google.com/console and gave him full admin rights (normally "see app information and download bulk reports" should be enough)
Added the role "Storage Object Viewer" to the Service account in https://console.cloud.google.com/iam-admin/iam?authuser=1&project=myproject
waited for 24h to make sure there are no errors because of syncs or so.
(I anonymized some of the values below).
Code example
from googleapiclient.discovery import build
from google.oauth2 import service_account
scopes = ['https://www.googleapis.com/auth/devstorage.read_only','https://www.googleapis.com/auth/cloud-platform.read_only']
key_file_location = 'files/access_token/mykeyfile.json'
cloud_storage_bucket = r'pubsite_prod_rev_00123456789'
report_to_download = 'installs/installs_com.my.app_202201_country.csv'
creds = service_account.Credentials.from_service_account_file(key_file_location,scopes=scopes)
service = build('storage','v1', credentials=creds)
print(service.objects().get(bucket = cloud_storage_bucket, object= report_to_download).execute())
Stack trace
Traceback (most recent call last):
File "C:\Users\myuser\project\z_10_ext_google_play_store.py", line 46, in <module>
print(service.objects().get(bucket = cloud_storage_bucket, object= report_to_download).execute())
File "D:\Programs\Python\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "D:\Programs\Python\lib\site-packages\googleapiclient\http.py", line 923, in execute
resp, content = _retry_request(
File "D:\Programs\Python\lib\site-packages\googleapiclient\http.py", line 191, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "D:\Programs\Python\lib\site-packages\google_auth_httplib2.py", line 209, in request
self.credentials.before_request(self._request, method, uri, request_headers)
File "D:\Programs\Python\lib\site-packages\google\auth\credentials.py", line 133, in before_request
self.refresh(request)
File "D:\Programs\Python\lib\site-packages\google\oauth2\service_account.py", line 410, in refresh
access_token, expiry, _ = _client.jwt_grant(
File "D:\Programs\Python\lib\site-packages\google\oauth2\_client.py", line 199, in jwt_grant
six.raise_from(new_exc, caught_exc)
File "<string>", line 3, in raise_from
google.auth.exceptions.RefreshError: ('No access token in response.', {'id_token': 'eyJ...'})
I hope that I provided enough information and I'm sorry in advance if I made a stupid mistake.

TwythonError: Twitter API returned a 404 for string 'usernames'

I am refering to this article.The article used twython to download user profile information with reference to UserID (int) and I am trying to use username(str).
The exact same code works when userID is given and when the same user's username is given this gives me an error.
what should I change in the program to read and process the usernames ? I have checked several question here and other forums the 404 is shown when the user is no longer available twitter user.
But to test that theory I did use same userid and username of which I can return the user profile fields but when the same user's username or screenname is used I am getting error.
Error:
Traceback (most recent call last):
File "user_prof_twython.py", line 25, in <module>
users = t.lookup_user(user_id = ids)
File "/usr/local/lib/python2.7/dist-packages/twython/endpoints.py", line 522, in lookup_user
return self.get('users/lookup', params=params)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 264, in get
return self.request(endpoint, params=params, version=version)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 258, in request
api_call=url)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 194, in _request
retry_after=response.headers.get('X-Rate-Limit-Reset'))
twython.exceptions.TwythonError: Twitter API returned a 404 (Not Found), No user matches for specified terms.
This works for me. Is this what you want?
Please note, screen_name can be a list. e.g.: ["aaaa","bbb","ccc","ddd"]
# Create a Twython instance with your application key and access token
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=1)
output = twitter.lookup_user(screen_name="BarackObama")
for user in output:
print user["id_str"]
print user['created_at']
print user['followers_count']

Instagram Client Error

I am new to the Instagram API. I used the following code from the example on the github to get the most recent popular media.
from instagram.client import InstagramAPI
id= "OMITTED"
secret = "OMITTED"
api = InstagramAPI(client_id=id, client_secret=secret)
popular_media = api.media_popular(count=20)
for media in popular_media:
print media.images['standard_resolution'].url
I get the following error:
File "example.py", line 6, in <module>
popular_media = api.media_popular(count=20)
File "/usr/lib/python2.6/site-packages/instagram/bind.py", line 197, in _call
return method.execute()
File "/usr/lib/python2.6/site-packages/instagram/bind.py", line 189, in execute
content, next = self._do_api_request(url, method, body, headers)
File "/usr/lib/python2.6/site-packages/instagram/bind.py", line 131, in _do_api_request
raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status'])
instagram.bind.InstagramClientError: (404) Unable to parse response, not valid JSON.
I know it is a valid instagram object because when I print(api). I get the following:
<instagram.client.InstagramAPI object at 0x145c2b10>
This is taken directly from the example and I can't tell what I am doing wrong! Any help would be great!
If u signed up after Nov 17th, Instagram popular photo feed is deprecated in new API.
The library you are using is old, it will only work for popular API if you had signed up for before November 17th
https://www.instagram.com/developer/changelog/

Having trouble trying to use gdata and oauth2 in python

Good evening, i've been trying to migrate my blogger python app to oauth2 since the good old Clientlogin() has been deprecated and erased.
So, basically i searched through the entire web and couldn't manage to make my application to work correctly.
This is the basic code im using for testing:
FLOW = flow_from_clientsecrets('/home/b/client_secret.json',scope='https://www.googleapis.com/auth/blogger',message="Client Secrets Not Found")
storage = Storage('blogger.dat')
credentials = storage.get()
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
if credentials is None or credentials.invalid:
credentials = run_flow(FLOW, storage, flags)
if credentials.access_token_expired:
credentials.refresh(httplib2.Http())
SCOPE = 'https://www.blogger.com/feeds'
token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
client = gdata.blogger.client.BloggerClient()
token.authorize(client)
post = client.add_post(blog_id, title="blah", body="blah", labels="label", draft=False, title_type="xhtml", body_type="html")
I get a 401 error code, unauthorized everytime i try to do this.
Traceback (most recent call last):
File "/home/b/.eclipse/org.eclipse.platform_4.4.2_1473617060_linux_gtk_x86_64/plugins/org.python.pydev_4.0.0.201504132356/pysrc/pydevd.py", line 2278, in <module>
globals = debugger.run(setup['file'], None, None)
File "/home/b/.eclipse/org.eclipse.platform_4.4.2_1473617060_linux_gtk_x86_64/plugins/org.python.pydev_4.0.0.201504132356/pysrc/pydevd.py", line 1704, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/b/workspace/BloggerPy/simpleblogger.py", line 53, in <module>
post = client.add_post(blog_id, title="hola", body="holaaa", labels="label", draft=False, title_type="xhtml", body_type="html", token=token)
File "/usr/local/lib/python2.7/dist-packages/gdata/blogger/client.py", line 111, in add_post
return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gdata/client.py", line 690, in post
desired_class=desired_class, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gdata/client.py", line 298, in request
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/gdata/client.py", line 307, in request
response, Unauthorized)
gdata.client.Unauthorized: Unauthorized - Server responded with: 401, User does not have permission to create new post
Can someone help me out with this? I'd really appreciate it :)
Greetings
Finally i've fixed my issue with gdata.gauth:
I used auth2token = gdata.gauth.OAuth2Token(client_id,client_secret,scope,user_agent)
After getting the authorization token i generate an authorized url to get an access code with auth2token.generate_authorize_url(redirect_uri=URL,approval_prompt="force").
once you get this url, you manually get the code and generate a refresh token, with which you generate an access token:
token = auth2token.get_access_token(code). Easy enough. For any other information as to how to save the token to a blob string in a file here's the reference:
gdata-python-api + Analytics with simple auth

How do I search for a user in Foursquare using the mLewisLogic python wrapper?

I'm having some trouble working with the Foursquare API. My end goal is to obtain a user's information (profile stats, twitter ids, facebooks ids, ...) from the Foursquare API. I would like to search for a user by either Twitter ID or name. My first attempt is using the foursquare recommended python wrapper called foursquare. Here is the documentation: https://github.com/mLewisLogic/foursquare
Here is my rather simple code:
import foursquare
client_id = xxx
client_secret = yyy
client = foursquare.Foursquare(client_id, client_secret)
print client.users.search(params={'twitter': 'nike'})
and here is my error:
Traceback (most recent call last):
File "D:\Users\nbush\workspace\Foursquare - API\main_foursq.py", line 12, in <module>
users = client.users.search(params={'twitter': 'nike'})
File "C:\Python27\lib\site-packages\foursquare\__init__.py", line 301, in search
return self.GET('search', params, multi=multi)
File "C:\Python27\lib\site-packages\foursquare\__init__.py", line 272, in GET
return self.requester.GET(self._expanded_path(path), *args, **kwargs)
File "C:\Python27\lib\site-packages\foursquare\__init__.py", line 200, in GET
result = _get(url, headers=headers, params=params)
File "C:\Python27\lib\site-packages\foursquare\__init__.py", line 787, in _get
return _process_response(response)
File "C:\Python27\lib\site-packages\foursquare\__init__.py", line 822, in _process_response
return _raise_error_from_response(data)
File "C:\Python27\lib\site-packages\foursquare\__init__.py", line 834, in
_raise_error_from_response
raise exc(meta.get('errorDetail'))
foursquare.NotAuthorized: A user is required to call this endpoint.
Any help would be great. Also if there is a better API or an easier way to do this with urllib2 or something then any suggestions would be appreciated. Alos, does anyone know if mLewisLogic is up to date with foursquare API v2? And is there a more complete documentation? Thanks in advance!
Add access_token
client = foursquare.Foursquare(client_id, client_secret, **access_token**)

Categories

Resources