我在尝试将照片上传到Facebook页面的脚本时遇到了一些问题。当只有字符串被传递时,我才能正常工作。页面帖子需要源文件(图像),这是我遇到问题的部分。这将返回400错误。
我不完全确定如何处理图像(目标是这样做是批量的,所以我理想地喜欢图像的zip文件。)
以下是正常工作的等效curl请求: curl -F'message = Book p://bit.ly/alaska'-F'ource=@alaska.jpg'-F' published = 0'-F'access_token = TEST'https://graph.facebook.com/act_id/photos
import os
import requests
import csv
import time
import thread
import zipfile
from datetime import datetime
from json import JSONEncoder
from flask import Flask, request, redirect, url_for, send_from_directory, \
render_template
from flask.ext.mail import Mail, Message
from werkzeug import secure_filename
email = ''
token=''
pageid = ''
filename = 'test.csv'
images = 'test.zip'
from flask import request
raw_input = open(filename, 'rb')
info = csv.DictReader(raw_input)
imagefile = zipfile.ZipFile(images, mode='r')
creation_date = datetime.now().strftime('%m-%d-%Y')
output_csv_name = \
"unpublished_posts_%s_%s.csv" % (pageid, creation_date)
output_csv = open(output_csv_name, 'wb')
writer = csv.writer(output_csv, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(('message',
'source',
'published',
'scheduled_publish_time',
'genders',
'age_max',
'age_min',
'countries',
'regions',
'cities',
'relationship_statuses',
'interested_in',
'locales',
'education_statuses',
'work_networks',
'college_networks',
'college_majors',
'college_years',
'post_id'
))
posts = []
targeting_params = ['genders',
'age_max',
'age_min',
'countries',
'regions',
'cities',
'relationship_statuses',
'interested_in',
'locales',
'education_statuses',
'work_networks',
'college_networks',
'college_majors',
'college_years']
for idx, row in enumerate(list(info)):
# convert date string to unix time-stamp
if row['scheduled_publish_time'] <> '':
s = row['scheduled_publish_time']
timestamp = \
time.mktime(datetime.strptime(s, "%d/%m/%Y").timetuple())
row['scheduled_publish_time'] = timestamp
post_params = [s for s in row.keys() if s not in targeting_params]
post_params.append('targeting')
for param in targeting_params:
if len(row[param]) > 0:
row[param] = row[param].split(",")
targeting_dict = {k: row[k] for k in targeting_params}
targeting_dict = dict([(k, v) for k, v in targeting_dict.items() \
if len(v) > 0])
row['targeting'] = JSONEncoder().encode(targeting_dict)
row = {k: row[k] for k in post_params}
row = dict([(k, v) for k, v in row.items() if len(v) > 0])
message = row['message']
row[u'message'] = u''.join(unichr(ord(c)) for c in row['message'])
imagename = row[u'source']
imagedata = imagefile.extract(imagename)
files = {'source': open(imagedata, 'rb')}
api_method = 'https://graph.facebook.com/%s/feed?access_token=%s'
response = requests.post(api_method % (pageid, token),params=row,files=files)
很抱歉,如果这还不够清楚的话。不确定什么是相关的,什么不是。我从我以前工作的脚本中改变的是在请求中添加了“文件”,所以我很确定这是我犯错的地方。
谢谢!
答案 0 :(得分:1)
试试这个:
files = { 'source': imagedata }
基本上你不能打开()imagedata
这已经是一个字符串(open()仅适用于文件),所以你只需按原样提交它,而请求将负责多部分编码。
另请查看有关使用请求进行文件上传的this问题。