找了一些使用微博pythonsdk的代码,但是都是python2.7版本,pipinstallsinaweibopy命令不能执行,因为python版本更新到3.7找到了一个经网友修改后的可执行的代码,按提示将网址复制到浏览器得到所需的code但是输入运行后出先如下图所示的问题。代码附上,以后慢慢修改#!/usr/bin/envpython#-*-coding:utf-8-*-__version__='1.04'__author__='LiaoXuefeng(askxuefeng@gmail.com)'__publish__='http://www.cnblogs.com/txw1958/''''Python3clientSDKforsinaweiboAPIusingOAuth2.'''try:importjsonexceptImportError:importsimplejsonasjsonimporttimeimporturllib.requestimportloggingdef_obj_hook(pairs):'''convertjsonobjecttopythonobject.'''o=JsonObject()fork,vinpairs.items():o[str(k)]=vreturnoclassAPIError(Exception):'''raiseAPIErrorifgotfailedjsonmessage.'''def__init__(self,error_code,error,request):self.error_code=error_codeself.error=errorself.request=requestException.__init__(self,error)def__str__(self):return'APIError:%s:%s,request:%s'%(self.error_code,self.error,self.request)classJsonObject(dict):'''generaljsonobjectthatcanbindanyfieldsbutalsoactasadict.'''def__getattr__(self,attr):returnself[attr]def__setattr__(self,attr,value):self[attr]=valuedef_encode_params(**kw):'''Encodeparameters.'''args=[]fork,vinkw.items():qv=v.encode('utf-8')ifisinstance(v,str)elsestr(v)args.append('%s=%s'%(k,urllib.parse.quote(qv)))return'&'.join(args)def_encode_multipart(**kw):'''Buildamultipart/form-databodywithgeneratedrandomboundary.'''boundary='----------%s'%hex(int(time.time()*1000))data=[]fork,vinkw.items():data.append('--%s'%boundary)ifhasattr(v,'read'):filename=getattr(v,'name','')n=filename.rfind('.')ext=filename[n:].lower()ifn!=(-1)else""content=v.read()content=content.decode('ISO-8859-1')data.append('Content-Disposition:form-data;name="%s";filename="hidden"'%k)data.append('Content-Length:%d'%len(content))data.append('Content-Type:%s\r\n'%_guess_content_type(ext))data.append(content)else:data.append('Content-Disposition:form-data;name="%s"\r\n'%k)data.append(vifisinstance(v,str)elsev.decode('utf-8'))data.append('--%s--\r\n'%boundary)return'\r\n'.join(data),boundary_CONTENT_TYPES={'.png':'image/png','.gif':'image/gif','.jpg':'image/jpeg','.jpeg':'image/jpeg','.jpe':'image/jpeg'}def_guess_content_type(ext):return_CONTENT_TYPES.get(ext,'application/octet-stream')_HTTP_GET=0_HTTP_POST=1_HTTP_UPLOAD=2def_http_get(url,authorization=None,**kw):logging.info('GET%s'%url)return_http_call(url,_HTTP_GET,authorization,**kw)def_http_post(url,authorization=None,**kw):logging.info('POST%s'%url)return_http_call(url,_HTTP_POST,authorization,**kw)def_http_upload(url,authorization=None,**kw):logging.info('MULTIPARTPOST%s'%url)return_http_call(url,_HTTP_UPLOAD,authorization,**kw)def_http_call(url,method,authorization,**kw):'''sendanhttprequestandexpecttoreturnajsonobjectifnoerror.'''params=Noneboundary=Noneifmethod==_HTTP_UPLOAD:params,boundary=_encode_multipart(**kw)else:params=_encode_params(**kw)http_url='%s?%s'%(url,params)ifmethod==_HTTP_GETelseurlhttp_body=Noneifmethod==_HTTP_GETelseparams.encode(encoding='utf-8')req=urllib.request.Request(http_url,data=http_body)ifauthorization:req.add_header('Authorization','OAuth2%s'%authorization)ifboundary:req.add_header('Content-Type','multipart/form-data;boundary=%s'%boundary)resp=urllib.request.urlopen(req)body=resp.read().decode("utf-8")r=json.loads(body,object_hook=_obj_hook)if'error_code'inr:raiseAPIError(r.error_code,r['error_code'],r['request'])returnrclassHttpObject(object):def__init__(self,client,method):self.client=clientself.method=methoddef__getattr__(self,attr):defwrap(**kw):ifself.client.is_expires():raiseAPIError('21327','expired_token',attr)return_http_call('%s%s.json'%(self.client.api_url,attr.replace('__','/')),self.method,self.client.access_token,**kw)returnwrapclassAPIClient(object):'''APIclientusingsynchronizedinvocation.'''def__init__(self,app_key,app_secret,redirect_uri=None,response_type='code',domain='api.weibo.com',version='2'):self.client_id=app_keyself.client_secret=app_secretself.redirect_uri=redirect_uriself.response_type=response_typeself.auth_url='https://%s/oauth2/'%domainself.api_url='https://%s/%s/'%(domain,version)self.access_token=Noneself.expires=0.0self.get=HttpObject(self,_HTTP_GET)self.post=HttpObject(self,_HTTP_POST)self.upload=HttpObject(self,_HTTP_UPLOAD)defset_access_token(self,access_token,expires_in):self.access_token=str(access_token)self.expires=float(expires_in)defget_authorize_url(self,redirect_uri=None,display='default'):'''returntheauthroizeurlthatshouldberedirect.'''redirect=redirect_uriifredirect_urielseself.redirect_uriifnotredirect:raiseAPIError('21305','Parameterabsent:redirect_uri','OAuth2request')return'%s%s?%s'%(self.auth_url,'authorize',\_encode_params(client_id=self.client_id,\response_type='code',\display=display,\redirect_uri=redirect))defrequest_access_token(self,code,redirect_uri=None):'''returnaccesstokenasobject:{"access_token":"your-access-token","expires_in":12345678},expires_inisstandardunix-epoch-time'''redirect=redirect_uriifredirect_urielseself.redirect_uriifnotredirect:raiseAPIError('21305','Parameterabsent:redirect_uri','OAuth2request')r=_http_post('%s%s'%(self.auth_url,'access_token'),\client_id=self.client_id,\client_secret=self.client_secret,\redirect_uri=redirect,\code=code,grant_type='authorization_code')r.expires_in+=int(time.time())returnrdefis_expires(self):returnnotself.access_tokenortime.time()>self.expiresdef__getattr__(self,attr):returngetattr(self.get,attr)defmain():try:#step1定义appkey,appsecret,回调地址:APP_KEY="525566084"APP_SECRET="98e8559d04d5bfd168322d4ecfd014fb"CALLBACK_URL='https://api.weibo.com/oauth2/default.html'#step2引导用户到授权地址client=APIClient(app_key=APP_KEY,app_secret=APP_SECRET,redirect_uri=CALLBACK_URL)print(client.get_authorize_url())#step3换取AccessToken#将上面的地址复制到浏览器中运行,输入账号密码授权,新的网址里面就有coder=client.request_access_token(input("Inputcode:"))#输入授权地址中获得的CODEclient.set_access_token(r.access_token,r.expires_in)##此时获取到access_token和expires_in应该保存下来,因为有一个有效期,如果短时间需要多次发微博,可以重复使用,而不需要每次获取。##step4使用获得的OAuth2.0AccessToken调用APIprint(client.get.account__get_uid())print(client.post.statuses__update(status='测试Python3+OAuth2.0发微博'+str(time.time())))#print(client.upload.statuses__upload(status='测试Python3OAuth2.0带图片发微博'+str(time.time()),pic=open('test.png','rb')))exceptExceptionaspyOauth2Error:print(pyOauth2Error)if__name__=='__main__':main()来源:灵境地平线