如何使用urllib将API密钥发送到Datadog?

时间:2018-06-13 01:18:41

标签: python urllib2 urllib urllib3 datadog

我目前有一个程序允许我以编程方式创建仪表板并将其发布到Datadog。使用API​​函数here,我成功地能够随意创建,更新和删除仪表板。但是,现在我想提取我已经从Datadog创建的现有仪表板的骨架,以查看已添加或删除的内容。为此,我需要弄清楚如何发送API密钥以及请求。获取有关电路板的更高级别信息我没有问题,但我想更进一步。

这是我通过调用api.ScreenBoard.get_all()

获得的
{
    'screenboards': [{
        'read_only': <boolean>,
        'resource': <resource-link>,
        'description': <description>,
        'created': <date>,
        'title': <text>,
        'modified': <date>,
        'created_by': { ''' <creator information> ''' },
        'id': <table-id>
    }]
}

现在,最终目标只是从&#34;资源&#34;中提取JSON。此命令给出的链接。我曾尝试使用urllib和urllib2将该链接与主机网站合并(例如https://www.foo.com/{resource-link}),但我会继续获得以下结果:

<addinfourl at 0000000000 whose fp = <socket._fileobject object at 0x000000000>>

OR

{"errors": ["API key required"]}

触发此错误的代码是:

def getSkeleton(self):
    boards = self.getAll(); # utilizing the api.ScreenBoards.get_all() function
    boardList = boards['screenboards'];
    for x in boardList:
        url = self.target + x['resource']; # creating the JSON url
        data = urllib.urlopen(url).read();
        print data

正如您所看到的,我的数据&#34;变量返回错误。因此,我需要的是弄清楚如何发送API密钥以及我的请求来解决问题。如果有人知道如何执行此任务,我将非常感激。

2 个答案:

答案 0 :(得分:0)

使用更简单的requests

生成像这样的请求标题

def headers(apikey):
    return {'Authorization': 'Bearer {}'.format(apikey),
            'Content-Type': 'application/json'}

发送此类请求

result = get(url, headers=headers(apikey))

答案 1 :(得分:0)

在搜索此other issue时,我发现修复此问题所需的只是在URL中指定API密钥和应用程序密钥。请考虑以下事项。

def indays(year,monthNum,day): ## year 
    leapyears = get_leapYear() ## monthNumber is "01,02 etc" 

    day_inYear = 365            ## day is day
    years_in_days = 0

    month_in_days = 0            

    for y in range(year): #this right here gets the year, and adds a year for every year in the range

        if y in leapyears:
            day_inYear = 366 ##checks if leapyear from the first function index, if it is, it adds 366 days instead of 365
        else:
            day_inYear = 365

        years_in_days = years_in_days + day_inYear

    for m in range(monthNum): #same thing as year, but months
        month = intLength[m]

        if monthNum == 1: ##sometimes i write a function that works, but forget how it works 2 days later.
            month_in_days = day ##i think if the date is in Jan, instead of getting "31" it just get's the given day.
        else:
            month_in_days = month_in_days + month

    sinceAD = years_in_days + month_in_days + day  #adds them up

    return sinceAD