3

I am requesting data from an api with a json response. The json content is dynamically changing all the time. I would like my python script to continuously run and look in the json for example every 5 seconds, until a given statement is true, which could be when a given userid number is present in the json response. When the userid number is present, then make an action, for example print userid and the connected username also found in the json response.

I have been looking at the polling documentation but I can't figure out how to use it the way I want to.

I wan't to poll data['result']['page']['list'] for ['user_id'] every 5 seconds and when ['user_id'] is True then print the information connected to the user_id like the nick_name.

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']))
aquatic7
  • 615
  • 1
  • 6
  • 19

2 Answers2

4

What about a simple loop ?

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)

If you want to have this run continously, you would loop infinitely (until interrupted) and log the events to a file like this:

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()
QuantumLicht
  • 2,103
  • 3
  • 23
  • 32
  • A simple loop might work. But I don't want to print it every 5 seconds. I want to look for it every 5 seconds and when it is there then just execute an action 1 time (for example print it 1 time). – aquatic7 Nov 28 '19 at 15:38
  • I adjusted the code. We now loop until we find one occurrence. – QuantumLicht Nov 28 '19 at 15:53
  • If that solves your problem, please consider accepting this answer to help future users. – QuantumLicht Nov 28 '19 at 17:33
  • It solved my problem, kinda, just not with polling which I wanted to learn since I think I could use that for more complex configurations. My question was just a bare minimum for me to work with. But instead I learned something else :) Is it possible to have it "listen" to when the 'user_id' is no longer present in the json and then again 'listen' to when the 'user_id' is present again and print the text? Like if I want it to keep running 24/7 until I manually end it to keep a log of every time a given user_id has been present? – aquatic7 Nov 28 '19 at 19:38
  • 1
    If you want to keep a log of events, you can use the `logging` module in the standard library. – QuantumLicht Nov 28 '19 at 19:52
  • I am sorry if don't explain myself good enough. The important thing is not logging. I want to do other stuff too. The important thing and what I am trying to accomplish is to have it run all the time. "Poll if 'user_id' is present -> if used_id is present do some action fx. print -> Poll for the 'user_id' not to be present anymore -> if 'user_id' is not present -> (Restart) Poll if the 'user_id' is present. – aquatic7 Nov 28 '19 at 20:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/203274/discussion-between-quantumlicht-and-aquatic7). – QuantumLicht Nov 28 '19 at 20:20
2

Using the polling library for the same

import polling
import json
userid = input('Input userID: ')
 polling.poll(
    lambda: json.loads(requests.post('https://website.com/api', headers=headers, data=data).text)['result']['page']['list']['user_id'] == userid,
    step=5,
    poll_forever=True)
response = requests.post('https://website.com/api',headers=headers, data=data)
data=json.loads(response.text)
print(data['result']['page']['list']['user_id'])

To change number of seconds change value in step. We poll every 5 seconds for matching user id and when we do find it another request is made to retrieve the value to print.

Shashank
  • 23
  • 3