Просмотр исходного кода

Upgrade uvicorn & starlette (#4563)

* Upgrade uvicorn, starlette

* Add missing import

* Use UJSONResponse

* Drop erronous 'self' references
Tom Christie 6 лет назад
Родитель
Сommit
fef2b7a526

+ 15 - 19
frameworks/Python/starlette/app.py

@@ -3,7 +3,8 @@ import asyncpg
 import os
 import jinja2
 from starlette.applications import Starlette
-from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse
+from starlette.responses import HTMLResponse, UJSONResponse, PlainTextResponse
+from starlette.routing import Route
 from random import randint
 from operator import itemgetter
 from urllib.parse import parse_qs
@@ -54,25 +55,15 @@ loop = asyncio.get_event_loop()
 loop.run_until_complete(setup_database())
 
 
-app = Starlette()
-
-
[email protected]('/json')
-def json_serialization(request):
-    return JSONResponse({'message': 'Hello, world!'})
-
-
[email protected]('/db')
 async def single_database_query(request):
     row_id = randint(1, 10000)
 
     async with connection_pool.acquire() as connection:
         number = await connection.fetchval(READ_ROW_SQL, row_id)
 
-    return JSONResponse({'id': row_id, 'randomNumber': number})
+    return UJSONResponse({'id': row_id, 'randomNumber': number})
 
 
[email protected]('/queries')
 async def multiple_database_queries(request):
     num_queries = get_num_queries(request)
     row_ids = [randint(1, 10000) for _ in range(num_queries)]
@@ -84,10 +75,9 @@ async def multiple_database_queries(request):
             number = await statement.fetchval(row_id)
             worlds.append({'id': row_id, 'randomNumber': number})
 
-    return JSONResponse(worlds)
+    return UJSONResponse(worlds)
 
 
[email protected]('/fortunes')
 async def fortunes(request):
     async with connection_pool.acquire() as connection:
         fortunes = await connection.fetch('SELECT * FROM Fortune')
@@ -98,7 +88,6 @@ async def fortunes(request):
     return HTMLResponse(content)
 
 
[email protected]('/updates')
 async def database_updates(request):
     num_queries = get_num_queries(request)
     updates = [(randint(1, 10000), randint(1, 10000)) for _ in range(num_queries)]
@@ -110,9 +99,16 @@ async def database_updates(request):
             await statement.fetchval(row_id)
         await connection.executemany(WRITE_ROW_SQL, updates)
 
-    return JSONResponse(worlds)
+    return UJSONResponse(worlds)
+
 
+routes = [
+    Route('/json', UJSONResponse({'message': 'Hello, world!'})),
+    Route('/db', single_database_query),
+    Route('/queries', multiple_database_queries),
+    Route('/fortunes', fortunes),
+    Route('/updates', database_updates),
+    Route('/plaintext', PlainTextResponse(b'Hello, world!')),
+]
 
[email protected]('/plaintext')
-def plaintext(request):
-    return PlainTextResponse(b'Hello, world!')
+app = Starlette(routes=routes)

+ 1 - 1
frameworks/Python/starlette/benchmark_config.json

@@ -10,7 +10,7 @@
       "update_url": "/updates?queries=",
       "port": 8080,
       "approach": "Realistic",
-      "classification": "Platform",
+      "classification": "Micro",
       "framework": "starlette",
       "language": "Python",
       "flavor": "Python3",

+ 3 - 3
frameworks/Python/starlette/requirements.txt

@@ -1,6 +1,6 @@
-asyncpg==0.16.0
+asyncpg==0.18.3
 gunicorn==19.9.0
-starlette==0.3.0
 jinja2==2.10
+starlette==0.12.0.b1
 ujson==1.35
-uvicorn==0.3.3
+uvicorn==0.7.0.b1

+ 112 - 140
frameworks/Python/uvicorn/app.py

@@ -75,175 +75,147 @@ def get_num_queries(scope):
     return query_count
 
 
-class JSONSerialization:
+async def json_serialization(scope, receive, send):
     """
     Test type 1: JSON Serialization
     """
-    def __init__(self, scope):
-        pass
+    content = json_dumps({'message': 'Hello, world!'}).encode('utf-8')
+    await send(JSON_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
 
-    async def __call__(self, receive, send):
-        content = json_dumps({'message': 'Hello, world!'}).encode('utf-8')
-        await send(JSON_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
 
-
-class SingleDatabaseQuery:
+async def single_database_query(scope, receive, send):
     """
     Test type 2: Single database object
     """
-    def __init__(self, scope):
-        pass
-
-    async def __call__(self, receive, send):
-        row_id = randint(1, 10000)
-        connection = await pool.acquire()
-        try:
-            number = await connection.fetchval(READ_ROW_SQL, row_id)
-            world = {'id': row_id, 'randomNumber': number}
-        finally:
-            await pool.release(connection)
-
-        content = json_dumps(world).encode('utf-8')
-        await send(JSON_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
+    row_id = randint(1, 10000)
+    connection = await pool.acquire()
+    try:
+        number = await connection.fetchval(READ_ROW_SQL, row_id)
+        world = {'id': row_id, 'randomNumber': number}
+    finally:
+        await pool.release(connection)
 
+    content = json_dumps(world).encode('utf-8')
+    await send(JSON_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
 
 
-class MultipleDatabaseQueries:
+async def multiple_database_queries(scope, receive, send):
     """
     Test type 3: Multiple database queries
     """
-    def __init__(self, scope):
-        self.scope = scope
-
-    async def __call__(self, receive, send):
-        num_queries = get_num_queries(self.scope)
-        row_ids = [randint(1, 10000) for _ in range(num_queries)]
-        worlds = []
-
-        connection = await pool.acquire()
-        try:
-            statement = await connection.prepare(READ_ROW_SQL)
-            for row_id in row_ids:
-                number = await statement.fetchval(row_id)
-                worlds.append({'id': row_id, 'randomNumber': number})
-        finally:
-            await pool.release(connection)
-
-        content = json_dumps(worlds).encode('utf-8')
-        await send(JSON_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
-
-
-class Fortunes:
+    num_queries = get_num_queries(scope)
+    row_ids = [randint(1, 10000) for _ in range(num_queries)]
+    worlds = []
+
+    connection = await pool.acquire()
+    try:
+        statement = await connection.prepare(READ_ROW_SQL)
+        for row_id in row_ids:
+            number = await statement.fetchval(row_id)
+            worlds.append({'id': row_id, 'randomNumber': number})
+    finally:
+        await pool.release(connection)
+
+    content = json_dumps(worlds).encode('utf-8')
+    await send(JSON_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
+
+
+async def fortunes(scope, receive, send):
     """
     Test type 4: Fortunes
     """
-    def __init__(self, scope):
-        pass
-
-    async def __call__(self, receive, send):
-        connection = await pool.acquire()
-        try:
-            fortunes = await connection.fetch('SELECT * FROM Fortune')
-        finally:
-            await pool.release(connection)
-
-        fortunes.append(ADDITIONAL_ROW)
-        fortunes.sort(key=key)
-        content = template.render(fortunes=fortunes).encode('utf-8')
-        await send(HTML_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
-
-
-class DatabaseUpdates:
+    connection = await pool.acquire()
+    try:
+        fortunes = await connection.fetch('SELECT * FROM Fortune')
+    finally:
+        await pool.release(connection)
+
+    fortunes.append(ADDITIONAL_ROW)
+    fortunes.sort(key=key)
+    content = template.render(fortunes=fortunes).encode('utf-8')
+    await send(HTML_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
+
+
+async def database_updates(scope, receive, send):
     """
     Test type 5: Database updates
     """
-    def __init__(self, scope):
-        self.scope = scope
-
-    async def __call__(self, receive, send):
-        num_queries = get_num_queries(self.scope)
-        updates = [(randint(1, 10000), randint(1, 10000)) for _ in range(num_queries)]
-        worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]
-
-        connection = await pool.acquire()
-        try:
-            statement = await connection.prepare(READ_ROW_SQL)
-            for row_id, _ in updates:
-                await statement.fetchval(row_id)
-            await connection.executemany(WRITE_ROW_SQL, updates)
-        finally:
-            await pool.release(connection)
-
-        content = json_dumps(worlds).encode('utf-8')
-        await send(JSON_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
-
-
-class Plaintext:
+    num_queries = get_num_queries(scope)
+    updates = [(randint(1, 10000), randint(1, 10000)) for _ in range(num_queries)]
+    worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]
+
+    connection = await pool.acquire()
+    try:
+        statement = await connection.prepare(READ_ROW_SQL)
+        for row_id, _ in updates:
+            await statement.fetchval(row_id)
+        await connection.executemany(WRITE_ROW_SQL, updates)
+    finally:
+        await pool.release(connection)
+
+    content = json_dumps(worlds).encode('utf-8')
+    await send(JSON_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
+
+
+async def plaintext(scope, receive, send):
     """
     Test type 6: Plaintext
     """
-    def __init__(self, scope):
-        pass
-
-    async def __call__(self, receive, send):
-        content = b'Hello, world!'
-        await send(PLAINTEXT_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
-
+    content = b'Hello, world!'
+    await send(PLAINTEXT_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
 
-class Handle404:
-    def __init__(self, scope):
-        pass
 
-    async def __call__(self, receive, send):
-        content = b'Not found'
-        await send(PLAINTEXT_RESPONSE)
-        await send({
-            'type': 'http.response.body',
-            'body': content,
-            'more_body': False
-        })
+async def handle_404(scope, receive, send):
+    content = b'Not found'
+    await send(PLAINTEXT_RESPONSE)
+    await send({
+        'type': 'http.response.body',
+        'body': content,
+        'more_body': False
+    })
 
 
 routes = {
-    '/json': JSONSerialization,
-    '/db': SingleDatabaseQuery,
-    '/queries': MultipleDatabaseQueries,
-    '/fortunes': Fortunes,
-    '/updates': DatabaseUpdates,
-    '/plaintext': Plaintext,
+    '/json': json_serialization,
+    '/db': single_database_query,
+    '/queries': multiple_database_queries,
+    '/fortunes': fortunes,
+    '/updates': database_updates,
+    '/plaintext': plaintext,
 }
 
 
-def main(scope):
+async def main(scope, receive, send):
     path = scope['path']
-    return routes.get(path, Handle404)(scope)
+    handler = routes.get(path, handle_404)
+    await handler(scope, receive, send)

+ 3 - 3
frameworks/Python/uvicorn/requirements.txt

@@ -1,5 +1,5 @@
-asyncpg==0.16.0
+asyncpg==0.18.3
+gunicorn==19.9.0
 jinja2==2.10
 ujson==1.35
-uvicorn==0.3.3
-gunicorn==19.9.0
+uvicorn==0.7.0.b1