Facebook api graph access token - python

there is any way to get the access token automatically with python using login informations ?
Something like this :
import requests
r=requests.get('https://graph.facebook.com/oauth/access_token?grant_type=get_token&
client_id=idclient_secret=password&privilege=')
print r.text

As far as I know you can't get users access token without users interaction.
You can get app token though like this:
facebook.get_app_access_token(APP_ID, APP_SECRET)
To get APP_ID and APP_SECRET you need to create new app here: https://developers.facebook.com/ Note that you will get much less meta data using app's token than using user's token.
I was writing script collecting data from facebook lately and I had same problem. I just switched to app token since my script runs every hour as cron job so it was impossible to deliver new token every time manually.

Related

Is there anyway for my python script to automatically get access token for working in Dropbox API

I am trying to build an python application for my server to run 24 hours and overwrite a file in dropbox every minute. When I built this application it stopped working after an hours for new token. I can't awake 24 hour to add new token every token. I just want a way that help me in doing setup of this. With dropbox there is no option to remove short length expire from token. Please keep it simple to underatnd easily dropbox documentation is hard for me to understand.
I just want a solution for this problem. I tried refresh token but it also required user interaction so no use.
Using refresh tokens is the right solution here. Just like with Dropbox access tokens, manual user interaction is required initially to get a Dropbox refresh token, but once the app has a refresh token it can store and re-use it repeatedly without further manual user interaction.
For reference, Dropbox is in the process of switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.
Apps can still get long-term access by requesting "offline" access though, in which case the app receives a "refresh token" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. You can find more information in the OAuth Guide and authorization documentation.
You can find examples of using the OAuth app authorization flow in the Dropbox Python SDK here.

Having trouble using cached tokens with Spotipy for Spotify?

I'm trying to use Spotipy to access a user's Spotify library but am running into a bit of trouble. For background, I'm using Flask, SQLAlchemy, and Flask-Login.
I looked off of this tutorial on github to get started, but this one doesn't quite work for me because if you use a cache, all users can access the playlist of the user whose token is cached, and since there is a cached token, any user after the first user can't login to Spotify. Here is some initial setup:
sp_oauth = oauth2.SpotifyOAuth(os.environ['SPOTIPY_CLIENT_ID'],
os.environ['SPOTIPY_CLIENT_SECRET'],
os.environ['SPOTIPY_REDIRECT_URI'],
scope="user-library-read")
To solve this, I first tried storing each user's access code in my database (I'm using SQLAlchemy as well). It looked something like this (under the method for the page that Spotipy redirects to with the access code):
if request.args.get("code"):
dbsession.query(User).get(current_user.uid).addService(
request.args["code"])
dbsession.commit()
However, this route is meant to return the names of the playlists the user owns, so I want it to be accessible without having to go through the Spotify authorization URL every time as long as the user is logged in. So, in the case where request.args["code"] is null, I try:
token_info = sp_oauth.get_access_token(dbsession.query(User)
.get(current_user.uid)
.getService())
spotify = spotipy.Spotify(token_info["access_token"])
Then I try to access the user using this instance of Spotify. However, using the stored access code (unsurprisingly) gives me a Bad Request error. I'm not sure what to do about getting a new code, or what I should store so that I don't need to cache but can still get credentials to access the playlists. Alternatively, is there a way that I can cache but only have certain users access certain tokens in the cache?
Thanks!
You can use the memory cache handler from the spotipy library to store the acess token in memory instead of the disk:
https://github.com/plamere/spotipy/blob/master/spotipy/cache_handler.py
You can also take a look at the example flask app in the examples directory:
https://github.com/plamere/spotipy/blob/master/examples/app.py

gdata python: store OAuth2Token

I am writing an app that is supposed to work with Google contacts.
So at some point I do the authentication with OAuth2:
token = OAuth2Token(client_id=client_info["client_id"],
client_secret=client_info["client_secret"],
scope=CLIENT_SCOPE,
user_agent=USER_AGENT)
# I open a webserver and browser until I retrieve the
# Auth code in a variable named "code"
token.get_access_token(code)
As of now, this flow starts every time the app accesses contatcs.
How do i make my application remember the authentication?
Does it have to do with refresh tokens, and if so, how does that works?
Yes, you should save the refresh token (depending on your system configuration) that is exchanged using the code..
Next time the script runs, it should look for the refresh token first and should try to use it. If it doesn't find it or the refresh token doesn't work, it should try to get the new code.

Python 3: Spotify Add Song To Public Playlist

So currently I have in place a system using Flask running on my localhost:8080 to add 1 song at a time to a public Spotify playlist. Unfortunately how I have implemented this it requires a browser to add a song. What I want to be able to do is URLLIB or possibly the REQUESTS library to do this without a browser. I have been unsuccessful in my attempts to do this bot URLLIB and REQUESTS only see the first page of my local host it is never redirected to my call back in the code that I linked below.
My Implementation
How would I go about implemented a non browser interface to add a song to a playlist? (Mind you this is python 3)
In order to add a song to a playlist, you need the playlist's owner to grant access to your application, so you will need a web interface at some point to carry out this step.
It's important that you obtain the access token using the Authorization Code Flow since that's how you will get an access token and a refresh token. Use that refresh token in your app to obtain access tokens without having the user to re-authorize your app.
So in brief:
Implement a web site that uses the Authorization Code. A user logs in and you obtain an access token and refresh token. Using the refresh token you will be able to generate access tokens without the user having to input their credentials.
Take the refresh token and include it in your script. Before making the request to add a track, obtain a fresh access token using the refresh token.
It's a bit cumbersome but that's the only way to use OAuth2 without exposing the user's username+password to an app.

gdata-python-api + Analytics with simple auth

I'm working on converting a Python script using the Google gdata API client + user/pass authentication to something more suitable for production (an API key). I am pretty frustrated with the muddled state of their documentation on authentication. I admittedly don't have a great grasp of OAuth2, but it seems like it's way more complicated for my usage case, which is: Hit Google Analytics every 24 hours to get the X most popular articles on our site.
In this scenario, we're not dealing with modifying someone's personal data, and all activity is centered on one account. It doesn't seem like OAuth2 is worth the complexity for something so simple.
I see that on the Google API Console (https://code.google.com/apis/console/), I've registered there and notice that there's a "Simple API Access" section with one key beneath the "Client ID for web applications" (which appears to be OAuth2). There's also the Google domain update page, https://www.google.com/accounts/UpdateDomain, but that appears to be OAuth related.
Is there any way to use this Simple API Access key (not OAuth) for retrieving analytics data with the Python gdata client, and if so, does anyone have any authentication examples? I already have the data retrieval stuff working once authenticated, but I'm using the user/pass approach, which is not appropriate for production.
Greg,
If you are already using the library gdata-python-client, this is relatively easy to do if you are the only user that your application will be authorizing.
The general mechanisms were detailed in a blog post in September, 2011, but I'll describe them here for completeness.
Part 1: Go to the APIs console and start a new project.
Part 2: From the project, go to "Services" and enable "Analytics API"
Part 3: From the project, go to "API Access" and click "Create an OAuth 2.0 client ID..." (you'll need to provide a product name, though the value you provide won't matter). When asked for the application type, select "Installed Application" and then "Create client ID". Since you will be the only user, you will only need one refresh token, and you can get this by authorizing from a desktop application a single time.
Part 4: Get your client id and client secret from the APIs console and then create an empty token:
import gdata.gauth
CLIENT_ID = 'id-from-apis-console'
CLIENT_SECRET = 'secret-from-apis-console'
SCOPE = 'https://www.google.com/analytics/feeds/' # Default scope for analytics
token = gdata.gauth.OAuth2Token(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPE,
user_agent='application-name-goes-here')
I got the scope from GData FAQ, though I'm not sure if it is correct.
Part 5: Use the token to create authorization URL for you to visit:
url = token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')
Since your application is an "Installed Application", your redirect URI is the default 'urn:ietf:wg:oauth:2.0:oob'. (Also note, the blog post had a typo and used the keyword argument redirect_url.)
Part 6: Visit the url and authorize your application to make requests on behalf of your account. After authorizing, you'll be redirected to a page with a code on it. This code will be used to exchange for an access token and a long-lived refresh token. The code has a life of 10 minutes and the access token has a life of an hour. The refresh token will allow you to get new access tokens for signing requests in perpetuity (or until you revoke the permission from your account).
Part 7: Use the code to get an access token:
code = 'random-string-from-redirected-page'
token.get_access_token(code) # This returns the token, but also changes the state
This again differs slightly from the blog post, because we are using an installed application.
Part 8: With the token you can now make all requests you want to make to the analytics client:
import gdata.analytics.client
client = gdata.analytics.client.AnalyticsClient()
token.authorize(client)
This is the big money right here. When an access token expires, the API requests signed with that token are rejected. However, by authorizing the client as above, when the said requests fail, the token attempts to use the refresh token to obtain a new access token. If it successfully obtains a new access token, the client resends the original API request, signed with the new access token.
I don't know anything about the Analytics API so I won't provide any more details there.
Future Use Note 1: Saving information for future use. You can re-use this from different places and after this use very easily. There are methods called token_to_blob and token_from_blob provided by the library that allow turning a token into a string and converting out of a string:
saved_blob_string = gdata.gauth.token_to_blob(token)
Once you have done this, you can store the string in a file and kill your running Python process. When you'd like to use it again:
saved_blob_string = retrieve_string_from_file() # You'll need to implement this
token = gdata.gauth.token_from_blob(saved_blob_string)
Future Use Note 2: This token will be able to be used to authorize a client and perform all your magic again and again, so long as you have the refresh token around. If for some reason you would like to get an access token again without calling token.generate_authorize_url, you'll need to manually set this on the object:
token.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
Future Use Note 3: Also, if you lose your refresh token and would like to get another one without having to go to the browser to revoke the original, you can use the approval_prompt parameter to get a new refresh token by visiting the url generated by:
url = token.generate_authorize_url(
redirect_uri='urn:ietf:wg:oauth:2.0:oob',
approval_prompt='force')

Categories