|
2 | 2 |
|
3 | 3 | import logging |
4 | 4 | import argparse |
5 | | -from concurrent import futures |
| 5 | +import concurrent.futures |
6 | 6 | import asyncio |
7 | 7 | from aiohttp import web |
8 | | -import json |
9 | 8 | import loganalyzer as analyze |
10 | 9 |
|
11 | | -loop = asyncio.get_event_loop() |
12 | | -threadPool = futures.ThreadPoolExecutor(thread_name_prefix='loganalyzer: worker thread') |
13 | | -app = web.Application() |
14 | | - |
15 | 10 | with open("templates/index.html", "r") as f: # Grab main HTML page |
16 | 11 | htmlTemplate = f.read() |
17 | 12 |
|
@@ -172,29 +167,29 @@ def sync_request_handler(request): |
172 | 167 |
|
173 | 168 | async def request_handler(request): |
174 | 169 | """Async request handler. Submits the incoming request to the thread pool to be handled.""" |
175 | | - return (await loop.run_in_executor(None, sync_request_handler, request)) # Submits the request to a handler inside the threadpool |
| 170 | + return await asyncio.to_thread(sync_request_handler, request) # Submits the request to a handler inside the threadpool |
| 171 | + |
| 172 | + |
| 173 | +async def on_startup(app): |
| 174 | + threadPool = concurrent.futures.ThreadPoolExecutor(thread_name_prefix='loganalyzer: worker thread') |
| 175 | + loop = asyncio.get_running_loop() |
| 176 | + loop.set_default_executor(threadPool) # Set the default executor to our thread pool |
176 | 177 |
|
177 | 178 |
|
178 | 179 | def main(): |
179 | 180 | logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] [%(funcName)s] %(message)s") |
180 | 181 | aiohttpLogger = logging.getLogger('aiohttp') |
181 | 182 | aiohttpLogger.setLevel(logging.WARNING) |
| 183 | + |
182 | 184 | parser = argparse.ArgumentParser() |
183 | 185 | parser.add_argument("--host", default="localhost", type=str, help="address to bind to", dest='host') |
184 | 186 | parser.add_argument("--port", default="8080", type=int, help="port to bind to", dest='port') |
185 | 187 | flags = parser.parse_args() |
186 | 188 |
|
187 | | - loop.set_default_executor(threadPool) # Set the default executor to our thread pool |
188 | | - app.add_routes([web.get('/', request_handler)]) |
189 | | - applicationTask = loop.create_task(web._run_app(app, host=flags.host, port=flags.port, print=logging.info)) |
190 | | - try: |
191 | | - loop.run_forever() |
192 | | - except KeyboardInterrupt: |
193 | | - pass |
194 | | - finally: |
195 | | - logging.info('Exiting application.') |
196 | | - applicationTask.cancel() # Shuts down the HTTP server |
197 | | - threadPool.shutdown() # Shuts down the running thread pool |
| 189 | + app = web.Application() |
| 190 | + app.on_startup.append(on_startup) |
| 191 | + app.router.add_get('/', request_handler) |
| 192 | + web.run_app(app, host=flags.host, port=flags.port) |
198 | 193 |
|
199 | 194 |
|
200 | 195 | if __name__ == '__main__': |
|
0 commit comments