gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:55:26 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com