将CURL翻译成Python——用于Twitter API

将CURL翻译成Python——用于Twitter API,python,api,twitter,Python,Api,Twitter,我希望通过Python“请求”获取Twitter参与度指标(印象、收藏夹等)。我可以通过以下代码获得授权: client_key = '*{Client Key}*' client_secret = '*{Client Secret}*' import base64 key_secret = '{}:{}'.format(client_key,client_secret).encode('ascii') b64_encoded_key = base64.b64encode(key_secr

我希望通过Python“请求”获取Twitter参与度指标(印象、收藏夹等)。我可以通过以下代码获得授权:

client_key = '*{Client Key}*'
client_secret = '*{Client Secret}*' 

import base64

key_secret = '{}:{}'.format(client_key,client_secret).encode('ascii')
b64_encoded_key = base64.b64encode(key_secret)
b64_encoded_key = b64_encoded_key.decode('ascii')

import requests

base_url = 'https://api.twitter.com/'
auth_url = '{}oauth2/token'.format(base_url)

auth_headers = {
    'Authorization':'Basic {}'.format(b64_encoded_key),
    'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
}

auth_data = {
    'grant_type':'client_credentials'
}

auth_resp = requests.post(auth_url, headers = auth_headers, data=auth_data)
但是,我不知道如何将下面的CURL转换为Python代码:

curl --request POST 
  --url https://data-api.twitter.com/insights/engagement/totals 
  --header 'accept-encoding: gzip' 
  --header 'authorization: Bearer ' 
  --header 'content-type: application/json' 
  --data '{
                "tweet_ids": [
                    "1070059276213702656","1021817816134156288","1067094924124872705"
                ],
                "engagement_types": [
                    "favorites","retweets","replies","video_views"
                ],
                "groupings": {
                    "perTweetMetricsUnowned": {
                        "group_by": [
                            "tweet.id",
                            "engagement.type"
                        ]
                    }
                }
            } 
  --verbose 
  --compressed
Twitter API参考:

有人有解决办法吗?提前谢谢


大多数人会使用Tweepy来传输Twitter数据。然而,我一直在寻找的是观察Tweet在整个时间段内的传递情况,因此我必须使用Tweepy没有涵盖的“”端点

应该只能够创建数据和标题字典并发布:

标题={
“接受编码”:“gzip”,
“授权”:“持票人”,
“内容类型”:“应用程序/json”,
}
数据={
“tweet_id”:[
"1070059276213702656","1021817816134156288","1067094924124872705"
],
“约定类型”:[
“收藏夹”、“转发”、“回复”、“视频视图”
],
“分组”:{
“PertweetMetricUnowned”:{
“分组人”:[
“tweet.id”,
“订婚。类型”
]
}
}
}
req=requests.post(
"https://data-api.twitter.com/insights/engagement/totals",
标题=标题,
数据=数据
)

刚刚注意到,这与身份验证代码片段中的身份验证方法完全相同!谢谢你的帮助!我意识到这个API端点是一个需要付费的高级版本。需要注意的一点是,您需要访问订婚API才能正常工作-这是一个付费API。