json - 带有已安装库的 Python 3.1 推特帖子,

标签 json twitter python-3.x urlencode

我希望能够从 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/

相关文章:

php访问json中的属性

javascript - 在Loadrunner中解析json响应

Php Twitter 帖子图片

android - 改造未正确接收响应

python - 比较同一文件夹的两个版本并获取不同的文件名

javascript - 无法用数据填充智能菜单 jquery 网格

java - Apache TomEE Webprofile 8 - 无法将 Json Rest 提供程序从 Johnzon 更改为 Jackson

jquery - 使用 jquery 的类似 Twitter 的状态消息

python - Tweepy exists_friendship 不存在?

python - 创建无限循环生成器的巧妙方法?