【问题标题】:Python 3.1 twitter post with installed library,已安装库的 Python 3.1 twitter 帖子,
【发布时间】:2011-02-18 02:59:18
【问题描述】:

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

我想知道标准库是否可以对其进行格式化以便发送消息。我的脑袋说这应该是可能的。

【问题讨论】:

    标签: json twitter python-3.x urlencode


    【解决方案1】:

    试试这个:

    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 方法将请求发送到 Twitter。当你传递一些数据时,它使用POST,否则使用GET

    这仅使用 Python3 标准库的一部分。但是,如果您想使用 HTTP,您应该重新考虑使用第三方库。这个Dive Into Python 3 chapter 解释了如何以及为什么。

    【讨论】:

    • 工作就像一个魅力, - 任何其他尝试它的人的注意点,如果你发送相同的消息两次它会抛出异常。
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多