gpt4 book ai didi

python - oauth2 发布 - 推特

转载 作者:行者123 更新时间:2023-12-01 03:43:53 25 4
gpt4 key购买 nike

我创建了一个脚本来获取用户好友列表(GET 请求)并且我成功了。现在我正在尝试制作一个跟随特定用户(POST 请求)的脚本,但我没有成功。

这是我的 oauth 函数(问题所在):

def augment_POST(url,**kwargs) :
secrets = hidden.oauth()
consumer = oauth2.Consumer(secrets['consumer_key'], secrets['consumer_secret'])
token = oauth2.Token(secrets['token_key'],secrets['token_secret'])

oauth_request = oauth2.Request.from_consumer_and_token(consumer, token= token, http_method='POST', http_url=url, parameters=kwargs)
oauth_request.to_postdata() # this returns post data, where should i put it?
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
return oauth_request.to_url()

我的augment_GET函数是完全相同的,除了http_mehtod='GET'

为了清楚起见:

def follow_user(id):
seedurl="https://api.twitter.com/1.1/friendships/create.json"
print 'Attempting to follow: %d' % (id,)
url = augment_POST(seedurl,user_id=id)
connection = urllib.urlopen(url)
data = connection.read()
headers = connection.info().dict

任何帮助将不胜感激。

最佳答案

首先,您似乎需要导入 urllib2 才能发出 POST 请求。
您必须发送从 to_postdata 方法获取的 POST 数据使用 urlopendata 参数:

def augment_POST(url, **kwargs) :
secrets = hidden.oauth()
consumer = oauth2.Consumer(secrets['consumer_key'],
secrets['consumer_secret'])
token = oauth2.Token(secrets['token_key'],
secrets['token_secret'])

oauth_request = oauth2.Request.from_consumer_and_token(
consumer,
token= token,
http_method='POST',
http_url=url,
parameters=kwargs
)

oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(),
consumer, token)

# this is the data that must be sent with you POST request
return oauth_request.to_postdata()


def follow_user(id):
url = "https://api.twitter.com/1.1/friendships/create.json"
print 'Attempting to follow: %d' % id
postdata = augment(url, method='GET', user_id=id)

# Send the POST request with the data argument
# The url is the same as the data is sent in the body of the request
connection = urllib2.urlopen(url, data=postdata)

data = connection.read()
headers = connection.info().dict
<小时/>

我建议使用 requests_oauthlib 模块,这使得这一切变得非常简单:

from requests_oauthlib import OAuth1Session

tokens = hidden.oauth()
client = OAuth1Session(tokens['consumer_key'],
tokens['consumer_secret'],
tokens['token_key'],
tokens['token_secret'])


def follow_user(id):
url = "https://api.twitter.com/1.1/friendships/create.json"
print 'Attempting to follow: %d' % id

# for GET requests use client.get and the `params` argument
# instead of the `data` argument
response = client.post(url, data={'user_id': id})

data = response.text
# or even `data = response.json()` to decode the data
headers = response.headers

关于python - oauth2 发布 - 推特,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235198/

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