我正在从事一个项目,该项目涉及从 Python 将图像上传到 tumblr。我很幸运使用 Tumblr 的 API ( http://www.tumblr.com/docs/en/api ) 来做常规的文本帖子,但是图片上传给我带来了麻烦。他们的服务器返回的错误消息仅限于告诉我有一个“上传照片错误”,这并没有帮助。
由于他们的 API 似乎基于使用标准 HTTP POST 操作,我知道必须有办法做到这一点。不幸的是,我这几天没有任何进展,我决定求助于你们。
我尝试过使用 curl 和 python 的库:httplib、urllib、urllib2 和名为 urllib2_file 的第三方库(http://fabien.seisen.org/python/urllib2_file/)。我很沮丧我没有让它们工作——但我愿意尝试你能想出的其他额外的终端应用程序。
每种方法都适用于简单的文本帖子,但每种方法似乎都无法正确完成照片上传。
这是我使用 urllib2_file 执行此操作的语法。由于 urllib2 不支持上传数据的“multipart/form-data”方法,我正在使用 urllib2_file 添加该功能——但我无法让它工作。tumblr api 说他们的服务器接受 multipart/form-data 以及上传文件的“正常发布”方法。如果任何一个工作,我会很高兴。
import urllib, urllib2, urllib2_file
url = "http://www.tumblr.com/api/write"
values1 = { 'email':'EMAIL',
'password':'PASSWORD',
'type':'regular',
'title':'Pythons urllib2',
'body':'its pretty nice. Not sure how to make it upload stuff yet, though. Still getting some "error uploading photo" errors... So unhelpful.'}
values2 = { 'email':'EMAIL',
'password':'PASSWORD',
'type':'photo',
'data': open('../data/media/pics/2009/05-14/100_1167.JPG'),
'caption':'Caption'}
data = urllib.urlencode(values2)
print "just before defining the request"
req = urllib2.Request(url,data)
print "just before doing the urlopen."
#response = urllib2.urlopen(req)
try:
response = urllib2.urlopen(req)
except urllib2.URLError, e:
print e.code
print e.read()
print "figure out how to handle .read() properly"
#the_page = response.read()
#print the_page
print "done"
如果它有效,这将是理想的方式,因为使用字典来定义字段真的很容易,而且我可以让它在未来看起来更干净。
任何有关如何解决可能出现问题的建议都将不胜感激。在这一点上,我不知道如何了解可能出了什么问题。我希望我能关注 http RFC。
我一直在考虑在服务器上的计算机之间嗅探数据包——但逆向工程 HTTP 可能是矫枉过正。
谢谢!