|
| 1 | +from proxy_py import settings |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import asyncio |
| 6 | +import aiopg |
| 7 | +import sys |
| 8 | + |
| 9 | + |
| 10 | +dsn = 'dbname={} user={} password={} host=127.0.0.1'.format( |
| 11 | + settings.DATABASE_CONNECTION_KWARGS['database'], |
| 12 | + settings.DATABASE_CONNECTION_KWARGS['user'], |
| 13 | + settings.DATABASE_CONNECTION_KWARGS['password'], |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +async def fill_it(dir_path, table_name): |
| 18 | + print("start filling table {}".format(table_name)) |
| 19 | + |
| 20 | + pool = await aiopg.create_pool(dsn) |
| 21 | + async with pool.acquire() as conn: |
| 22 | + async with conn.cursor() as cur: |
| 23 | + # await cur.execute() |
| 24 | + |
| 25 | + file_path = os.path.join(dir_path, table_name + ".json") |
| 26 | + |
| 27 | + print("reading file {}".format(file_path)) |
| 28 | + with open(file_path) as file: |
| 29 | + print("filling database", end="") |
| 30 | + for i, line in enumerate(file): |
| 31 | + print(".", end="") |
| 32 | + sys.stdout.flush() |
| 33 | + |
| 34 | + line = line.strip() |
| 35 | + if line and line not in '[]': |
| 36 | + line = line[:-1] |
| 37 | + json_obj = json.loads(line) |
| 38 | + # print(json_obj) |
| 39 | + keys = [] |
| 40 | + values = [] |
| 41 | + for key, val in json_obj.items(): |
| 42 | + keys.append(key) |
| 43 | + values.append(val) |
| 44 | + |
| 45 | + sql_request = """ |
| 46 | + INSERT INTO {} ({}) |
| 47 | + VALUES ({}) |
| 48 | + ON CONFLICT DO NOTHING; |
| 49 | + """.format(table_name, ', '.join(keys), ', '.join(['%s' for _ in range(len(values))])) |
| 50 | + |
| 51 | + # print(sql_request.strip()) |
| 52 | + |
| 53 | + await cur.execute(sql_request, values) |
| 54 | + |
| 55 | + print() |
| 56 | + |
| 57 | + print() |
| 58 | + |
| 59 | + |
| 60 | +async def main(): |
| 61 | + if len(sys.argv) < 2: |
| 62 | + raise BaseException("Please, specify directory from which to load your dumps") |
| 63 | + |
| 64 | + load_from_dir = sys.argv[1] |
| 65 | + if not os.path.isdir(load_from_dir): |
| 66 | + raise BaseException("{} is not a directory".format(load_from_dir)) |
| 67 | + |
| 68 | + for filename in [filename for filename in os.listdir(load_from_dir) |
| 69 | + if os.path.isfile(os.path.join(load_from_dir, filename))]: |
| 70 | + table_name, _ = filename.split(".") |
| 71 | + await fill_it(load_from_dir, table_name) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == '__main__': |
| 75 | + loop = asyncio.get_event_loop() |
| 76 | + loop.run_until_complete(main()) |
0 commit comments