mobolic / facebook-sdk Goto Github PK
View Code? Open in Web Editor NEWPython SDK for Facebook's Graph API
Home Page: https://facebook-sdk.readthedocs.io/
License: Apache License 2.0
Python SDK for Facebook's Graph API
Home Page: https://facebook-sdk.readthedocs.io/
License: Apache License 2.0
Certain write operations in the Facebook API require post arguments that are JSON objects. Example: adgroup creation in the ads API (https://developers.facebook.com/docs/reference/ads-api/adgroup/#create) which expects certain objects such as conversion_specs, targeting, and tracking_specs.
When using put_object, if one passes a python dict as one of these arguments the call will fail with a "malformed JSON" or similar message. I got around it by doing a json.dumps() on each before passing them to put_object.
Don't know if the the library should handle this encoding or if it's out of scope, but FYI.
It took my some time to find out where the FQL functionality is. I tried graph.get_object('fql?q=...')
etc and spent some time then ended up reading the code. I think an example in README would be helpful for many people.
Hi, in the GAE example db is still used, while the GAE stardard is now ndb. Is there a reason to keep using the old db, or is possible to change the code for using the ndb?
The README on PyPi is currently showing Markdown syntax instead of being rendered properly.
../venv/bin/pip install facebook-sdk
Downloading/unpacking facebook-sdk
Could not find any downloads that satisfy the requirement facebook-sdk
No distributions at all found for facebook-sdk
This works fine though:
../venv/bin/pip install https://github.com/pythonforfacebook/facebook-sdk/tarball/master
../venv/bin/pip run on Wed Jan 18 11:56:29 2012
Downloading/unpacking facebook-sdk (from -r ../requirements.txt (line 6))
Getting page http://pypi.python.org/simple/facebook-sdk
URLs to search for versions for facebook-sdk (from -r ../requirements.txt (line 6)):
Hello!
I'm trying to do post to page feed
group_id = '130496407122821'
file_path = os.path.join('tmp', 'test.jpg')
file = open(file_path, 'rb')
graph.put_photo(file, 'API test', group_id)
This is did post to my personal feed, not to page feed.
Where is problem with it?
Python 2.7.3
facebook_sdk-0.3.2-py2.7.egg
graph.get_connections(profile["id"], "friends")
Traceback (most recent call last):
File "sdkref.py", line 31, in
friends = graph.get_connections(profile["id"], "friends")
File "C:\Program Files (x86)\Python27\lib\site-packages\facebook.py", line 111, in get_connections
return self.request(id + "/" + connection_name, args)
File "C:\Program Files (x86)\Python27\lib\site-packages\facebook.py", line 275, in request
raise GraphAPIError(response)
facebook.GraphAPIError: Unsupported operation
If you request the offline_access permission, the python sdk will think the user is logged in while the Facebook JS API thinks otherwise if the user is not actually logged into FB. It appears that two additional cookies are set "act", and "csm" and are removed by the JS API when you call FB.logout(). The "fbsr_" cookie is NOT removed by the JS API if the user has granted the offline_access permission.
I'm not sure exactly what these cookies are used for, but it seems that the python sdk may need to know about them to be consistent with the JS API.
Hi,
i tried your lib in combinaison of with your django-facebook
since your function :
def get_access_token_from_code(code, redirect_uri, app_id, app_secret):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
# We would use GraphAPI.request() here, except for that the fact
# that the response is a key-value pair, and not JSON.
response = urllib.urlopen("https://graph.facebook.com/oauth/access_token" +
"?" + urllib.urlencode(args)).read()
query_str = parse_qs(response)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
return result
else:
response = json.loads(response)
raise GraphAPIError(response)
get called on every request it can't work.
I added a revoke_auth method to the SDK, seems to work:
def revoke_auth(self, id):
self.request(id + '/permissions', post_args={"method": "delete"})
Tried to do a pull request online but Github errored.
$ pip install facebook-sdk
Downloading/unpacking facebook-sdk
Could not find any downloads that satisfy the requirement facebook-sdk
No distributions at all found for facebook-sdk
May be it's time to provide package on PyPi? :)
I found that there's get_app_access_token function for app access token but no any further APIs like creating or accessing test users.
I'm thinking of implementing all APIs from https://developers.facebook.com/docs/test_users/.
The new Facebook App requirements specify that a logout method is necessary. Any chance of adding this to the facebook-sdk? Thanks
I see that there is a method for extending token expiration, but It would be much more usable if facebook-sdk did it automatically.
There is a post that brings out the error messages that require the app to extend/re-request a token: https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
I think this would be a very strong feature for facebook-sdk, moreso since FB will deprecate offline-access shortly.
Thank you for your consideration in advance.
I am not able to upload any photo with the put_photo method.
In the documentation the first parameter is the filename, while in the method it seems a file-like object.
Passing a file like object as a first paramter (called image) I recevice an unicode conversion error.
Any idea how to fix this?
Thanks
I can search the logged in user's news stream with:
https://graph.facebook.com/me/home?q=youtube.com&access_token=XYZ
But how do I do this with facebook-sdk? I have:
friends = graph.get_connections("me", "home")
but this doesn't search for a particular term (like "youtube.com".
When I call parse_signed_request() with app_secret in unicode the hmac drops a TypeError exception:
"C:\Python26\lib\hmac.py", line 72, in __init__ self.outer.update(key.translate(trans_5C)) TypeError: character mapping must return integer, None or unicode
I have improved the library, how can i join the team to push the changes?
Sorry for the offtopic..
Since most requests go to the same servers, it would seem that Keep-alive and HTTP connection pooling would be extremely helpful for this library. Most of my application's delays are spent on urllib2 requests to the graph. Any chance of updating the code to use urllib3 or Requests that would likely speed up a query? In some benchmarks I've seen, they can be twice as fast.
Oh, and Requests support's Python 3, which may address this issue, since it appears most of it focuses on urllib queries.
Right now the SDK doesn't check the actual image format, and assumes it's a JPG: https://github.com/pythonforfacebook/facebook-sdk/blob/master/facebook.py#L261
Is there a way to issue batch requests?
I've tried get_objects() which successfully retrieves several objects. But I can't seem to retrieve in one request several object/connection.
For example, if ['1','2'] are album ids, get_objects(['1','2']) successfully gives me those 2 albums. But I can't seem to do something like get_objects(['1/photos','2/photos'])
Sorry, I (mis)used an issue ticket for this, but it was the only way to contact you all..
I just created the pythonforfacebook mailinglist to discuss about django/facebook integration, and I'd greatly appreciate if you guys would join it / advertise in the project description..
The mailinglist URL: http://groups.google.com/group/pythonforfacebook
Affected version: 0.4.0
I get the following error:
Message: [Errno socket error] [Errno -3] Temporary failure in name resolution
Method: facebook.get_user_from_cookie
The problem seems to be that urllib.urlopen
is being used which does not support HTTP CONNECT requests to talk to https://graph.facebook.com/oauth/access_token
from behind a proxy.
Using urllib2.urlopen
fixes this issue.
put_album used to exist on the GraphAPI and now it doesn't.
This happens when using the Facebook JavaScript SDK to generate a cookie. So in other words, it should be providing a fresh cookie always. Reloading the page fixes this issue but this is obviously not ideal UX and leads most users to think the site is broken.
Exception on /facebook/login [GET]
Traceback (most recent call last):
File "/srv/http/blueprint/trekseat/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app
response = self.full_dispatch_request()
File "/srv/http/blueprint/trekseat/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/srv/http/blueprint/trekseat/lib/python2.7/site-packages/flask/app.py", line 1262, in full_dispatch_request
rv = self.dispatch_request()
File "/srv/http/blueprint/trekseat/lib/python2.7/site-packages/flask/app.py", line 1248, in dispatch_request
return self.view_functionsrule.endpoint
File "/srv/http/blueprint/trekseat/frontend/views.py", line 799, in facebook_login
local user and determine if we should create a new user, in the case none
File "/srv/http/blueprint/trekseat/src/facebook-sdk/facebook.py", line 366, in get_user_from_cookie
app_id, app_secret)
File "/srv/http/blueprint/trekseat/src/facebook-sdk/facebook.py", line 434, in get_access_token_from_code
response["error"]["message"])
GraphAPIError: Code was invalid or expired. Session has expired at unix time 1325545200. The current unix time is 1325556761.
When running this in a Django app, I noticed this warning:
/home/username/.virtualenvs/envname/local/lib/python2.7/site-packages/facebook.py:52: DeprecationWarning: django.utils.simplejson is deprecated; use json instead.
from django.utils import simplejson as json
It's been deprecated since Django 1.5 (release notes). In theory, the json
module is a drop-in replacement for django.utils.simplejson
, so lines 51-53 could just be deleted; but because of incompatibilities between versions of simplejson
, it may trigger errors in some circumstances, according to the release notes.
I am trying to upload images to fanpage timeline ,
path = "/var/www/scheduler/media/userupload/3.jpg"
page_id = "XXXXXXXX"
access_token = "XXXXXX"
graph = facebook.GraphAPI(access_token)
resp = graph.put_photo(open(path),message="This is awesome test",page_id)
i am getting an error "(#324) Missing or invalid image file" , Can any one help me ? Is it an issue ?
How can i do this ?
Here is a simple file:
$ cat test.py
import facebook
g = facebook.GraphAPI('dummy_token')
g.api_request('search', args={'q': '[email protected]', 'type': 'user'})
When run, it produces the following error message:
$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
g.api_request('search', args={'q': '[email protected]', 'type': 'user'})
File "/Library/Python/2.7/site-packages/facebook.py", line 339, in api_request
if self.api_key:
AttributeError: 'GraphAPI' object has no attribute 'api_key'
When I pass app_secret as unicode string parse_signed_request() function raises an exception during hmac.new() call:
Exception Type: TypeError
Exception Value: character mapping must return integer, None or unicode
Exception Location: <python 2.7>\lib\hmac.py in init, line 72
It can be resolved by converting app_secret to string at the beginning of parse_signed_request() function.
From the server side when you use the graph API for access_token, you get it irrespective of the fact whether the user is logged in or not.
Given this, the 3rd paragraph of this routine which mentions of returning a dict with uid and access_token only if the user is logged in is not right.
Correcting this will help new comers (like me) who read the code before adopting it.
Best,
Ethan
Downloading/unpacking facebook-sdk (from -r requirements.txt (line 4))
Could not find any downloads that satisfy the requirement facebook-sdk (from -r requirements.txt (line 4))
No distributions at all found for facebook-sdk (from -r requirements.txt (line 4))
Storing complete log in /app/.pip/pip.log
Hi! Using graph.put_object('me', 'feed', message='message') it seems I'm only able to publish to the users wall, but not his newsfeed. How could I work around that? Thanks.
For some reason, images generated with PIL throw a UnicodeDecodeError when trying to upload to Facebook.
Tested opening the image in Photoshop and saved as a new copy, and that image uploaded fine.
Some more changes are needed to make the get_user_from_cookie
function work with the new Facebook OAuth2 login system.
Please see localpower/python-facebook-sdk@4e20521 for the changes I had to make to get it to work. (Those changes were pulled from https://gist.github.com/1190267)
The example from Google App Engine included with the project calls get_user_from_cookie
on every request, which now sends a request to Facebook. The example should cache the returned access token so that this does not happen.
A common error I keep getting in my apps is that the user's OAuth token has expired. It would be nice if the GraphAPI object had an option to auto renew the token whenever it gets this error.
There is a method for renewing the token in the GraphAPI object, extend_access_token(), but you have to wrap all api calls in try..except blocks, catch the error and check if it is a session expired error, renew the token, and then issue again the original api call.
Right now I'm implementing this pattern in a helper function that wraps all GraphAPI calls, but maybe it would be nice to have it included in the GraphAPI object itself.
Any opinions? Am I the only one having this issue?
-- EDIT: this issue is invalid. I miss understood the purpose of extend_access_token(). You can only extend a valid access token for one that expires in 60 days. But this has to be done when the short lived access_token is still valid... So my approach doesn't work.
I'm pretty sure that this is actually a bug on Facebook's side: https://developers.facebook.com/bugs/181323008674971
They claim to have fixed it by not reusing previous access tokens, but I don't know if that's actually true given a lot of the comments in the thread. However, it's probably worth checking the latest commits to the PHP SDK and seeing if there is anything that needs to be ported in with regards to this issue (which is INCREDIBLY frustrating).
I was trying to get the email address of the current user. I already added the email in the scope. Can't seem to display it to the HTML template using {{ current_user.email }}
Any plan to support a feature to send app notifications?
i've been running into a bunch of ssl related failures using this lib. i think its similar to this php issue:
http://oscarm.org/2012/4/fix-ssl-timeouts-facebook-php-sdk
not sure if there's anything this library should do about it, because its an openssl or python issue. but i figured i'd post here in case others have the issue.
(Pdb) image
<open file '/home/sontek/.virtualenvs/studiosnaps/src/studiosnaps/booth/photos/uploads/upload_11.jpg', mode 'r' at 0x147f4b0>
(Pdb) c
Traceback (most recent call last):
File "/home/sontek/.virtualenvs/studiosnaps/local/lib/python2.7/site-packages/gevent/greenlet.py", line 390, in run
result = self._run(_self.args, *_self.kwargs)
File "/home/sontek/.virtualenvs/studiosnaps/src/studiosnaps/booth/controller.py", line 114, in upload_photo
self.uploader.upload_photo(self.view.get_upload_file())
File "/home/sontek/.virtualenvs/studiosnaps/src/studiosnaps/booth/upload.py", line 283, in upload_photo
photo_response = fp_graph.put_photo(photo, '', album_id)
File "/home/sontek/.virtualenvs/studiosnaps/src/studiosnaps/booth/facebook.py", line 175, in put_photo
object_id = album_id or "me"
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 400, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 418, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1174, in do_open
h.request(req.get_method(), req.get_selector(), req.data, headers)
File "/usr/lib/python2.7/httplib.py", line 958, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py", line 992, in _send_request
self.endheaders(body)
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 812, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 413: ordinal not in range(128)
I'm just calling:
photo_response = graph_obj.put_photo(photo, '', album_id)
See Deprecation of Offline Access Permission, specifically the section titled "Client-side OAuth and Extending Access_Token Expiration Time through New Endpoint".
On most machines there is no timeout for urllib2.urlopen
:
>>> print socket.getdefaulttimeout()
None
I was doing quite a lot of fql queries and I have noticed that almost every four or five connection is broken - as there is no timeout the library waits for the broken connection thus the whole script is jammed, after I have added 3 seconds timeout everything was fine and even faster - facebook is sometimes extremely slow and restarting connection helps.
I'm getting a KeyError in line 251.
Exception Type: KeyError
Exception Value: 'error'
In my logs I can see that the response returned by facebook is:
response = {'error_code': 1, 'error_msg': 'An unknown error occurred'}
and doesn't have an "error" key.
Multiple comments on #47 ask that we document how to properly use pagination with the Graph API.
Hi
I'm beginner on developing apps on GAE and started with a simple app that uses facebook login. Got your code example (for facebook login on GAE) and discovered it doesn't work fine with Mozilla Firefox.
Here is my app: ciro-app-id.appspot.com
When the user logs in with the facebook account, Firefox starts some kind of infinite requests loop.
This log has been taken from GAE logs and repeats itself for each request made by Firefox:
2013-10-22 19:14:42.364 / 200 109ms 1kb Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
186.226.15.243 - - [22/Oct/2013:19:14:42 -0700] "GET / HTTP/1.1" 200 1303 - "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)" "ciro-app-id.appspot.com" ms=109 cpu_ms=70 cpm_usd=0.000146 app_engine_release=1.8.6 instance=00c61b117c5ef2a696a0544fcffd207dae4362
In other browsers, the code works perfectly.
What can you tell me to do?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.