在python中轮询特定json元素的api

2024-04-27 04:14:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个带有json响应的api请求数据。json内容一直在动态变化。我想让我的python脚本连续运行并查看json,例如每5秒一次,直到一个给定的语句为true,这可能是当json响应中存在一个给定的userid号时。 当用户标识号存在时,执行一个操作,例如打印用户标识和在json响应中找到的连接的用户名。你知道吗

我一直在看polling documentation,但我不知道如何使用它的方式,我想。你知道吗

我不想每5秒轮询data['result']['page']['list']一次['user_id'],当['user_id']为真时,打印连接到用户id的信息,如昵称。你知道吗

response = requests.post('https://website.com/api', headers=headers, data=data)

json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)

userid = input('Input userID: ')


for ps in data['result']['page']['list']:
    if userid == str(ps['user_id']):
        print('Username: ' + ps['nick_name'])
        print('UserID: ' + str(ps['user_id']))

Tags: 用户apiidjsondataresponsepageresult
1条回答
网友
1楼 · 发布于 2024-04-27 04:14:58

简单的循环怎么样?你知道吗

import time
found_occurrence = False
userid = input('Input userID: ')

while not found_occurrence:
 response = requests.post('https://website.com/api', headers=headers, data=data)
 json_res = response.json()
 for ps in json_res['result']['page']['list']:
    if userid == str(ps['user_id']):
        print('Username: ' + ps['nick_name'])
        print('UserID: ' + str(ps['user_id']))
        found_occurrence = True
 time.sleep(5)

如果您想继续运行,您可以无限循环(直到中断),并将事件记录到如下文件中:

import logging
import time
import sys
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')

userid = input('Input userID: ')
try: 
    while True:
     response = requests.post('https://website.com/api', headers=headers, data=data)
     json_res = response.json()
     for ps in json_res['result']['page']['list']:
        if userid == str(ps['user_id']):
           logging.info('Username: ' + ps['nick_name'])
           logging.info('UserID: ' + str(ps['user_id']))
     time.sleep(5)
except KeyboardInterrupt:
  logging.info("exiting")
  sys.exit()

相关问题 更多 >