python使用新浪微博api上传图片到微博示例

代码如下:

import urllib.parse,os.path,time,sysfrom http.client import httpsconnectionfrom pyqt5.qtcore import *from pyqt5.qtgui import *from pyqt5.qtwidgets import *

#pathospath=sys.path[0]if len(ospath)!=3: ospath+=’\\’ospath=ospath.replace(‘\\’,’/’)

#apiclass api: def sina(self,status,pic): fsize=os.path.getsize(pic) boundary=”$-img-lufei-goodboy-$” crlf=’\r\n’ data=[ #token ‘–‘+boundary, ‘content-disposition: form-data; name=”access_token”‘, ”, ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxx’,#你的access_token #status ‘–‘+boundary, ‘content-disposition: form-data; name=”status”‘, ”, status, #pic ‘–‘+boundary, ‘content-disposition: form-data; name=”pic”; filename=”q_17.jpg”‘, ‘content-type: image/jpeg’, ” ] #utf-8 data=(crlf.join(data)+crlf).encode(‘utf-8’) closing=’\r\n–‘+boundary+’–\r\n’ sumlen=len(data)+len(closing)+fsize #—————————————- h=httpsconnection(‘upload.api.weibo.com’) h.putrequest(‘post’,’/2/statuses/upload.json’) h.putheader(‘content-type’,’multipart/form-data; boundary=%s’ % boundary) h.putheader(‘content-length’,sumlen) h.endheaders() h.send(data) f=open(pic,’rb’) while true: data=f.read(12345) if not data: break h.send(data) f.close() h.send(closing.encode(‘utf-8’)) r=h.getresponse() return r.read().decode(‘utf-8′,’ignore’)api=api()#uiclass dialog(qdialog): def __init__(self): super().__init__() #icon,title self.setwindowicon(qicon(ospath+’weibo.ico’)) self.setwindowtitle(‘weibo’) #texteditor self.editor=qtextedit() #textline,filebutton,submit self.line=qlineedit() brows=qpushbutton(‘打开’) brows.clicked.connect(self.getfilename) submit=qpushbutton(‘发表’) submit.clicked.connect(self.submit) #layout layout=qgridlayout() layout.setcontentsmargins(0,0,0,0) #addwidget layout.addwidget(self.editor,0,0,1,2) layout.addwidget(self.line,1,0,1,1) layout.addwidget(brows,1,1,1,1) layout.addwidget(submit,2,0,1,2) #set self.setlayout(layout) def getfilename(self): filename=qfiledialog.getopenfilename() self.line.settext(filename[0]) def submit(self): status=self.editor.toplaintext() pic=self.line.text() self.editor.settext(api.sina(status,pic))app=qapplication(sys.argv)dialog=dialog()dialog.show()app.exec_()

发表评论