web-client.py 2.33 KB
import sys
import requests
import json
from datetime import datetime
from time import (
    sleep,
    time,
    )
from threading import Thread
from optparse import OptionParser


threads = {}
end_threads = []
durations = {}
json_responses = {}


def create_thread(func, args=[]):
    thread = Thread(target=func, args=args)
    # Exit the server thread when the main thread terminates
    thread.daemon = True
    return thread


def send(p):
    key = p['id']
    log_info('Request: {}'.format(p))
    start = time()
    try:
        resp = requests.post(url, data=json.dumps(p), headers=headers)
        durations[key] = time() - start
        json_resp = resp.json()
        log_info('Response: {}'.format(json_resp))
        json_responses[key] = json_resp
    finally:
        end_threads.append(key)


def log_info(s):
    t = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
    t = t[:-3]
    msg = '{} {}'.format(t, s)
    print(msg)


default_url = 'http://localhost:7000/rpc'
default_host = 'pemda'
default_count = 1

help_url = 'default ' + default_url
help_host = 'default ' + default_host
help_count = 'default {}'.format(default_count)

parser = OptionParser()
parser.add_option('', '--url', default=default_url, help=help_url)
parser.add_option('', '--host', default=default_host, help=help_host)
parser.add_option(
    '-c', '--count', type='int', default=default_count, help=help_count)
option, args = parser.parse_args(sys.argv[1:])

url = option.url
count = option.count
headers = {'content-type': 'application/json'}
p = {'host': option.host}
data = {
    'method': 'echo',
    'params': [p],
    'jsonrpc': '2.0',
    }
for i in range(count):
    data['id'] = i
    thread = create_thread(send, [dict(data)])
    threads[i] = thread

for key in threads: 
    thread = threads[key]
    thread.start()
    sleep(0.2)

while threads:
    sleep(1)
    if not end_threads:
        continue
    i = end_threads[0]
    if i in threads:
        thread = threads[i]
        thread.join()
        del threads[i]
    index = end_threads.index(i)
    del end_threads[index]

for key in durations:
    val = durations[key]
    resp = json_responses[key]
    if 'error' in resp:
        break
    result = resp['result']
    if result['code'] == 0:
        stan = result['data']['11']
    else:
        stan = '-'
    print('thread {} stan {} {} detik'.format(key, stan, val))