【问题标题】:Upload image to facebook using the Python API使用 Python API 将图像上传到 Facebook
【发布时间】:2016-03-27 10:15:16
【问题描述】:

我已经在网上广泛搜索了一个通过 Python API (Python for Facebook) 将照片上传到 facebook 的仍然有效的示例。以前在 stackoverflow 上有人问过这样的问题,但我找到的答案都没有了。

我的工作是:

import facebook as fb

cfg = {
    "page_id"      : "my_page_id",
    "access_token" : "my_access_token"
    }

api = get_api(cfg)
msg = "Hello world!"
status = api.put_wall_post(msg) 

我将 get_api(cfg) 函数定义为 this

graph = fb.GraphAPI(cfg['access_token'], version='2.2')

# Get page token to post as the page. You can skip
# the following if you want to post as yourself.
resp = graph.get_object('me/accounts')
page_access_token = None
for page in resp['data']:
    if page['id'] == cfg['page_id']:
        page_access_token = page['access_token']
graph = fb.GraphAPI(page_access_token)
return graph

这确实会在我的页面上发布消息。 但是,如果我想上传图片,一切都会出错。

# Upload a profile photo for a Page.
api.put_photo(image=open("path_to/my_image.jpg",'rb').read(), message='Here's my image')

我得到了可怕的 GraphAPIError: (#324) 需要上传文件,stackoverflow 上的解决方案都不适合我。 如果我改为发出以下命令

api.put_photo(image=open("path_to/my_image.jpg",'rb').read(), album_path=cfg['page_id'] + "/picture")

我得到 GraphAPIError: (#1) 无法获取图片,我也无法找到解决方案。

有人可以为我指出正确的方向,为我提供一个当前有效的示例吗?将不胜感激,谢谢!

【问题讨论】:

  • 图像必须是文件对象而不是上下文,而且您的行包含错误的单引号。未经测试,您应该尝试:api.put_photo(image=open("path_to/my_image.jpg",'rb'), message='Here\'s my image').
  • @KlausD。是的,我在发布问题的那一刻就看到了错误的引号,但为时已晚。但是,在我的真实代码中,我没有这样的标记。如果我尝试你的建议 api.put_photo(image=open("path_to/my_image.jpg",'rb'), message='Any message') 我仍然得到 GraphAPIError: (#324) Requires upload file i> 不过谢谢你的建议!
  • 你能列出你正在使用的文件和目录结构以及你的python调用从哪个目录开始
  • @phwd 我的 main.py 文件位于我的 facebook 文件夹所在的同一文件夹中(从 Facebook 的 Python 的 git 页面复制)此外,我将完整路径写入我的图像,如例如:“Drive:/folder/folder/image.jpg” 因此,我的工作文件夹包含以下 main.py image.jpg facebook(文件夹) facebook 文件夹包含 init.py 版本。 py 希望有帮助!
  • 在图片所在的文件夹中尝试curl -F 'source=@my_image.jpg' 'https://graph.facebook.com/me/photos?access_token=YOUR_TOKEN'。如果仍然返回 324 错误,则问题出在照片上。

标签: python facebook facebook-graph-api upload photo


【解决方案1】:

我知道这是旧的,并且没有使用指定的 API 回答问题,但是,我通过搜索发现了这个问题,希望我的解决方案能够帮助走类似道路的旅行者。

使用requeststempfile

我如何使用tempfilerequests 模块的简单示例。

下载图片并上传到 Facebook

下面的脚本应该从给定的 url 抓取图像,将其保存到临时目录中的文件中,并在完成后自动清理。

此外,我可以确认这可以在 Google Cloud Run 上的 Flask 服务上运行。这是容器运行时合约附带的,因此我们可以将文件存储在内存中

import tempfile
import requests

# setup stuff - certainly change this
filename = "your-desired-filename"           
filepath = f"{directory}/{filename}"
image_url = "your-image-url"
act_id = "your account id"
access_token = "your access token"

# create the temporary directory
temp_dir = tempfile.TemporaryDirectory()
directory = temp_dir.name

# stream the image bytes
res = requests.get(image_url, stream=True)
# write them to your filename at your temporary directory 
# assuming this works
# add logic for non 200 status codes
with open(filepath, "wb+") as f:
        f.write(res.content)

# prep the payload for the facebook call           
files = {
    "filename": open(filepath, "rb"),
}
url = f"https://graph.facebook.com/v10.0/{act_id}/adimages?access_token={access_token}"
# send the POST request
res = requests.post(url, files=files)
res.raise_for_status()
if res.status_code == 200:
    # get your image data back
    image_upload_data = res.json()
    temp_dir.cleanup()
    if "images" in image_upload_data:
        return image_upload_data["images"][filepath.split("/")[-1]]
    return image_upload_data
temp_dir.cleanup() # paranoid: just in case an error isn't raised 

【讨论】:

    【解决方案2】:

    324 Facebook 错误可能由多种原因导致,具体取决于照片上传调用的方式

    • 缺少图像
    • Facebook 无法识别图片
    • 目录路径引用不正确

    原始的 cURL 调用看起来像

    curl -F 'source=@my_image.jpg' 'https://graph.facebook.com/me/photos?access_token=YOUR_TOKEN'

    只要上述调用有效,您就可以确定照片与 Facebook 服务器一致。

    324 错误如何发生的示例

    touch meow.jpg

    curl -F 'source=@meow.jpg' 'https://graph.facebook.com/me/photos?access_token=YOUR_TOKEN'

    如您所见,损坏的图像文件也会发生这种情况。

    使用.read() 将转储实际数据

    空文件

    >>> image=open("meow.jpg",'rb').read()
    >>> image
    ''
    

    图像文件

    >>> image=open("how.png",'rb').read()
    >>> image
    '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00...
    

    正如您所见,这两种方法都不适用于api.put_photo 调用,Klaus D. 提到调用应该没有read()

    所以这个电话

    api.put_photo(image=open("path_to/my_image.jpg",'rb').read(), message='Here's my image')

    其实变成了

    api.put_photo('\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00...', message='Here's my image')

    这只是一个字符串,这不是我们想要的。

    需要图片参考<open file 'how.png', mode 'rb' at 0x1085b2390>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多