gpt4 book ai didi

python - 使用 FB graph api 和 app engine-python SDK 创建相册的代码是什么?

转载 作者:行者123 更新时间:2023-12-01 06:12:27 25 4
gpt4 key购买 nike

我在 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);

最佳答案

正如 Facebook 的人所写的 here ,他们将不再支持 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 发送多部分/表单数据的简短方法,所以我使用了这个答案 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'}

关于python - 使用 FB graph api 和 app engine-python SDK 创建相册的代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5052507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com