Browse Source

API-Hour FrameworkBenchmark: Migrate HTTP to aiohttp.web

Ludovic Gasc (GMLudo) 10 years ago
parent
commit
fad51ba9ca

+ 4 - 4
frameworks/Python/API-Hour/benchmark_config

@@ -1,16 +1,16 @@
 {
-  "framework": "API-Hour",
+  "framework": "aiohttp.web",
   "tests": [{
     "default": {
       "setup_file": "setup",
       "json_url": "/json",
       "db_url": "/db",
       "query_url": "/queries?queries=",
-      "port": 8000,
+      "port": 8008,
       "approach": "Realistic",
-      "classification": "Platform",
+      "classification": "Micro",
       "database": "Postgres",
-      "framework": "API-Hour",
+      "framework": "aiohttp.web",
       "language": "Python",
       "orm": "Raw",
       "platform": "API-Hour",

+ 7 - 9
frameworks/Python/API-Hour/hello/hello/__init__.py

@@ -1,12 +1,12 @@
 import logging
 import asyncio
+import os
 
 import aiopg
-import os
 import psycopg2.extras
+import aiohttp.web
 
 import api_hour
-import api_hour.aiorest
 
 from . import endpoints
 
@@ -18,21 +18,20 @@ class Container(api_hour.Container):
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         # Servers
-        self.servers['http'] = api_hour.aiorest.Application(*args, **kwargs)
+        self.servers['http'] = aiohttp.web.Application(loop=kwargs['loop'])
         self.servers['http'].ah_container = self # keep a reference to Container
         # routes
-        self.servers['http'].add_url('GET', '/json', endpoints.world.json)
-        self.servers['http'].add_url('GET', '/db', endpoints.world.db)
-        self.servers['http'].add_url('GET', '/queries', endpoints.world.queries)
+        self.servers['http'].router.add_route('GET', '/json', endpoints.world.json)
+        self.servers['http'].router.add_route('GET', '/db', endpoints.world.db)
+        self.servers['http'].router.add_route('GET', '/queries', endpoints.world.queries)
 
     def make_servers(self):
-        return [self.servers['http'].make_handler]
+        return [self.servers['http'].make_handler()]
 
     @asyncio.coroutine
     def start(self):
         yield from super().start()
         LOG.info('Starting engines...')
-        # Add your custom engine here, example with PostgreSQL:
         self.engines['pg'] = self.loop.create_task(aiopg.create_pool(host=os.environ.get('DBHOST', '127.0.0.1'),
                                                                      sslmode='disable',
                                                                      port=int(self.config['engines']['pg']['port']),
@@ -50,7 +49,6 @@ class Container(api_hour.Container):
     @asyncio.coroutine
     def stop(self):
         LOG.info('Stopping engines...')
-        # Add your custom end here, example with PostgreSQL:
         if 'pg' in self.engines:
             if self.engines['pg'].done():
                 self.engines['pg'].result().terminate()

+ 7 - 7
frameworks/Python/API-Hour/hello/hello/endpoints/world.py

@@ -1,7 +1,7 @@
 import logging
 import asyncio
-from random import randint
 
+from ..utils import JSON
 from ..services import queries_number
 from ..services.world import get_random_record, get_random_records
 
@@ -10,19 +10,19 @@ LOG = logging.getLogger(__name__)
 @asyncio.coroutine
 def json(request):
     """Test type 1: JSON serialization"""
-    return {'message': 'Hello, World!'}
+    return JSON({'message': 'Hello, World!'})
 
 @asyncio.coroutine
 def db(request):
     """Test type 2: Single database query"""
-    container = request.application.ah_container
+    container = request.app.ah_container
 
-    return (yield from get_random_record(container))
+    return JSON((yield from get_random_record(container)))
 
 @asyncio.coroutine
 def queries(request):
     """Test type 3: Multiple database queries"""
-    container = request.application.ah_container
-    limit = queries_number(request.args.get('queries', 1))
+    container = request.app.ah_container
+    limit = queries_number(request.GET.get('queries', 1))
 
-    return (yield from get_random_records(container, limit))
+    return JSON((yield from get_random_records(container, limit)))

+ 14 - 2
frameworks/Python/API-Hour/hello/hello/utils/__init__.py

@@ -1,4 +1,16 @@
 import logging
-import asyncio
 
-LOG = logging.getLogger(__name__)
+from aiohttp.web import Response
+import ujson
+
+LOG = logging.getLogger(__name__)
+
+class JSON(Response):
+    """Serialize response to JSON"""
+
+    def __init__(self, json, status=200,
+                 reason=None, headers=None):
+        body = ujson.dumps(json).encode('utf-8')
+
+        super().__init__(body=body, status=status, reason=reason,
+                         headers=headers, content_type='application/json')

+ 2 - 1
frameworks/Python/API-Hour/requirements.txt

@@ -4,4 +4,5 @@ gunicorn==19.1.1
 psycopg2==2.5.4
 setproctitle==1.1.8
 six==1.8.0
-ujson==1.33
+ujson==1.33
+aiohttp==0.13.1