我希望能够从 python 3.0 发布 Twitter 消息。我看过的所有 twitter API 都不支持 python 3.1。由于后期程序只需要这个:
JSON: curl -u username:password -d status="your message here" http://api.twitter.com/1/statuses/update.json
我想知道是否可以使用标准库对其进行格式化以便发送消息。我的头脑说这应该是可能的。
最佳答案
试试这个:
import urllib.request
import urllib.parse
import base64
def encode_credentials(username, password):
byte_creds = '{}:{}'.format(username, password).encode('utf-8')
return base64.b64encode(byte_creds).decode('utf-8')
def tweet(username, password, message):
encoded_msg = urllib.parse.urlencode({'status': message})
credentials = encode_credentials(username, password)
request = urllib.request.Request(
'http://api.twitter.com/1/statuses/update.json')
request.add_header('Authorization', 'Basic ' + credentials)
urllib.request.urlopen(request, encoded_msg)
然后调用 tweet('username', 'password', 'Hello twitter from Python3!')
。
urlencode
函数为 HTTP POST
请求准备消息。
Request
对象使用 HTTP 身份验证,如下所述:http://en.wikipedia.org/wiki/Basic_access_authentication
urlopen
方法将请求发送到推特。当您向它传递一些数据时,它使用 POST
,否则使用 GET
。
这仅使用了 Python3 标准库的一部分。但是,如果您想使用 HTTP,您应该重新考虑使用第三方库。这Dive Into Python 3 chapter解释如何以及为什么。
关于json - 带有已安装库的 Python 3.1 推特帖子,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2810500/