如何使用FB Graph API和App Engine的Python SDK创建相册?

1 投票
2 回答
1605 浏览
提问于 2025-04-16 12:08

我在PHP中找到了以下代码……

那么在Python中,做同样事情的代码是什么呢?

//At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);

//Create an album
$album_details = array(
        'message'=> 'Album desc',
        'name'=> 'Album name'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);

//Get album ID of the album you've just created
$album_uid = $create_album['id'];

//Upload a photo to album of ID...
$photo_details = array(
    'message'=> 'Photo message'
);
$file='app.jpg'; //Example image file
$photo_details['image'] = '@' . realpath($file);

$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);

2 个回答

0

这个功能不被Facebook支持,不过你可以考虑一下这个链接:http://code.google.com/p/gae-simpleauth/,它可以帮助你处理oauth的部分。

然后,正如其他回答提到的,你可以使用Python的一些库,比如urllib2,来进行图形接口的调用(可能还需要用到simplejson来解析返回的数据)。

2

正如Facebook的开发者在这里所说,他们将不再支持Python的Facebook SDK,所以最好使用Python自带的工具来发送请求。

创建相册:

import urllib,urllib2
access_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXX"
path = "me/albums"
post_args = {'access_token':access_token,'name':"Test Album5", 'message':"Test Album 5"}
post_data  = urllib.urlencode(post_args)
file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" , post_data)
response = file.read() 

>>>response
'{"id":"XXXXXX702571"}'

上传图片:

我没有找到用urllib2发送multipart/form数据的简单方法,所以我参考了这个回答中的例子https://stackoverflow.com/a/6843405/592737

import pycurl
import cStringIO

url = 'https://graph.facebook.com/ALBUM_ID/photos'
file ='/path/to/img.jpg'

response = cStringIO.StringIO()
c = pycurl.Curl()
values = [
    ('file' , (c.FORM_FILE,  file)),
  ('access_token' , access_token),
  ('message' , 'Image Message'),
  ]


c.setopt(c.POST, 1)
c.setopt(c.URL,url)
c.setopt(c.HTTPPOST,  values)
#c.setopt(c.VERBOSE, 1)
c.setopt(c.WRITEFUNCTION, response.write)
c.perform()
c.close()

>>>response.getvalue()
{"id":"XXXXXX07961"}

但是如果你使用的是某个Facebook Python SDK的分支(比如https://github.com/pythonforfacebook/facebook-sdk),你可以用更简单的方法来实现:

import facebook
access_token = "XXXXXXXXXXXXXXXXXXXXXXXX"
graph = facebook.GraphAPI(access_token)
resp = graph.put_object("me", "albums", name="Test Album",message="Test description")
graph.put_photo(open('/path/to/img.jpg'), 'Look at this cool photo!', resp['id'])
>>> _
{'id': '4394545113756'}

撰写回答