遍历Rocket.Chat API

时间:2019-03-04 14:00:23

标签: python python-3.x api rocket.chat

Python 3.7.2 PyCharm

我对Python和API交互还很陌生;我正在尝试遍历Rocket Chat的API,特别是拉出用户电子邮件地址。 与我可以找到的几乎每个示例不同,Rocket Chat不使用“ Next”之类的任何结构-它使用的是count和offset 尽管这可能会更容易。 我已经设法完成了这项工作的第一部分, 遍历JSON并获取电子邮件。我需要做的是遍历API端点-这是我遇到的一些问题。
我已经看过这个答案Unable to loop through paged API responses with Python 因为它似乎很接近我想要的,但是我无法使其正常工作。

下面的代码是我现在拥有的;显然,这还没有通过API端点进行任何循环,只是循环返回的json。

import os
import csv
import requests
import json

url = "https://rocketchat.internal.net"
login = "/api/v1/login"
rocketchatusers = "/api/v1/users.list"
#offset = "?count=500&offset=0"


class API:

    def userlist(self, userid, token):
        headers = {'X-Auth-Token': token, 'X-User-Id': userid}
        rocketusers = requests.get(url + rocketchatusers, headers=headers, verify=False)
        print('Status Code:' + str(rocketusers.status_code))
        print('Content Type:' + rocketusers.headers['content-type'])
        userlist = json.loads(rocketusers.text)
        x = 0
        y = 0
        emails = open('emails', 'w')
        while y == 0:
            try:
                for i in userlist:
                    print(userlist['users'][x]['emails'][0]['address'], file=emails)
                    # print(userlist['users'][x]['emails'][0]['address'])
                    x += 1
            except KeyError:
                print("This user has no email address", file=emails)
                x += 1
            except IndexError:
                print("End of List")
                emails.close()
                y += 1

我尝试过的事情和我想做的事情都是沿着简单的FOR循环进行的。实际上,可能有很多方法可以完成我要执行的操作,但我只是不了解。

类似这样的东西:

import os
import csv
import requests
import json

url = "https://rocketchat.internal.net"
login = "/api/v1/login"
rocketchatusers = "/api/v1/users.list"
offset = "?count=500&offset="+p
p = 0

class API:

    def userlist(self, userid, token):
        headers = {'X-Auth-Token': token, 'X-User-Id': userid}
        rocketusers = requests.get(url + rocketchatusers+offset, headers=headers, verify=False)

        for r in rocketusers:
            print('Status Code:' + str(rocketusers.status_code))
            print('Content Type:' + rocketusers.headers['content-type'])
            userlist = json.loads(rocketusers.text)
            x = 0
            y = 0
            emails = open('emails', 'w')
            while y == 0:
                try:
                    for i in userlist:
                        print(userlist['users'][x]['emails'][0]['address'], file=emails)
                        # print(userlist['users'][x]['emails'][0]['address'])
                        x += 1
                except KeyError:
                    print("This user has no email address", file=emails)
                    x += 1
                except IndexError:
                    print("End of List")
                    emails.close()
                    y += 1
        p += 500

现在,显然这行不通,或者我不打算发布,但是为什么不行是问题所在。 得到报告的错误是,当需要STR时,我无法连接INT。好的。当我尝试类似的事情时:

str(p = 0) 我收到类型错误。我也尝试了很多其他事情,其中​​许多只是愚蠢的事情,例如p = [],p = {}和其他更激进的想法。

URL(如果不是所有变量且已串联)看起来像这样:

https://rocketchat.internal.net/api/v1/users.list?count=500&offset=0
https://rocketchat.internal.net/api/v1/users.list?count=500&offset=500
https://rocketchat.internal.net/api/v1/users.list?count=500&offset=1000
https://rocketchat.internal.net/api/v1/users.list?count=500&offset=1500

我觉得我真的缺少一些简单的东西。我有把握确定答案是对我列出的帖子的答复,但我无法使它正常工作。

1 个答案:

答案 0 :(得分:0)

因此,在四处询问之后,我发现我一直在寻找解决此问题的正确方法上,只是在错误的地方尝试过。这就是我最终得到的:

def userlist(self, userid, token):
    p = 0
    while p <= 7500:
        if not os.path.exists('./emails'):
            headers = {'X-Auth-Token': token, 'X-User-Id': userid}
            rocketusers = requests.get(url + rocketchatusers + offset + str(p), headers=headers, verify=False)
            print('Status Code:' + str(rocketusers.status_code))
            print('Content Type:' + rocketusers.headers['content-type'])
            print('Creating the file "emails" to use to compare against list of regulated users.')
            print(url + rocketchatusers + offset + str(p))
            userlist = json.loads(rocketusers.text)
            x = 0
            y = 0
            emails = open('emails', 'a+')
            while y == 0:
                try:
                    for i in userlist:
                        #print(userlist['users'][x]['emails'][0]['address'], file=emails)
                        print(userlist['users'][x]['ldap'], file=emails)
                        print(userlist['users'][x]['username'], file=emails)
                        x += 1
                except KeyError:
                    x += 1
                except IndexError:
                    print("End of List")
                    emails.close()
                    p += 50
                    y += 1
        else:
            headers = {'X-Auth-Token': token, 'X-User-Id': userid}
            rocketusers = requests.get(url + rocketchatusers + offset + str(p), headers=headers, verify=False)
            print('Status Code:' + str(rocketusers.status_code))
            print('Content Type:' + rocketusers.headers['content-type'])
            print('Populating file "emails" - this takes a few moments, please be patient.')
            print(url + rocketchatusers + offset + str(p))
            userlist = json.loads(rocketusers.text)
            x = 0
            z = 0
            emails = open('emails', 'a+')
            while z == 0:
                try:
                    for i in userlist:
                        #print(userlist['users'][x]['emails'][0]['address'], file=emails)
                        print(userlist['users'][x]['ldap'], file=emails)
                        print(userlist['users'][x]['username'], file=emails)
                        x += 1
                except KeyError:
                    x += 1
                except IndexError:
                    print("End of List")
                    emails.close()
                    p += 50
                    z += 1

这仍在进行中,不幸的是,这不是合作的途径,稍后我可以将其发布到GitHub上,以便其他人可以看到它。