Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.1 kB
2
Indexable
Never
import argparse
import asyncio
import datetime
import aiohttp
import json

class DataFetcher:
    def __init__(self, url):
        self.url = url

    async def fetch_data(self):
        async with aiohttp.ClientSession() as session:
            async with session.get(self.url) as response:
                data = await response.text()
                return data

class DataParser:
    def parse_data(self, data):
        raise NotImplementedError

class Data1Parser(DataParser):
    def parse_data(self, data):
        json_data = json.loads(data)
        parsed_data = json_data[0]['userId']
        return parsed_data

class Data2Parser(DataParser):
    def parse_data(self, data):
        json_data = json.loads(data)
        parsed_data = json_data[0]['postId']
        return parsed_data

class QueryHandler:
    def __init__(self, data_fetcher, data_parser):
        self.data_fetcher = data_fetcher
        self.data_parser = data_parser

    async def query_data(self):
        data = await self.data_fetcher.fetch_data()
        parsed_data = self.data_parser.parse_data(data)
        return parsed_data

async def main(handler_num):
    if handler_num == 1:
        data_fetcher1 = DataFetcher('https://jsonplaceholder.typicode.com/posts')
        data_parser1 = Data1Parser()
        query_handler1 = QueryHandler(data_fetcher1, data_parser1)
        result1 = await query_handler1.query_data()
        print(f'Query result 1: {result1} at {datetime.datetime.now()}')
    elif handler_num == 2:
        data_fetcher2 = DataFetcher('https://jsonplaceholder.typicode.com/comments')
        data_parser2 = Data2Parser()
        query_handler2 = QueryHandler(data_fetcher2, data_parser2)
        result2 = await query_handler2.query_data()
        print(f'Query result 2: {result2} at {datetime.datetime.now()}')
    else:
        print('Incorrect handler_num')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--handler', choices=['1', '2'], help='Specify the type of data handler to use')
    args = parser.parse_args()
    asyncio.run(main(int(args.handler)))