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

本文展示了如何利用Python结合新浪API实现上传图片到微博的功能。通过创建`Api`类并设置请求参数,结合`HTTPClient`发送POST请求,可以成功发布包含图片的状态。此外,还提供了一个简单的UI对话框,用户可以输入文字和选择图片进行发布。
摘要由CSDN通过智能技术生成

import urllib.parse,os.path,time,sys

from http.client import HTTPSConnection

from PyQt5.QtCore import *

from PyQt5.QtGui import *

from PyQt5.QtWidgets import *

#path

ospath=sys.path[0]

if len(ospath)!=3:

ospath+='\\'

ospath=ospath.replace('\\','/')

#api

class 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()

#ui

class 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_()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值