"""The same application code is loaded by every server in the comparison."""
import asyncio
import os
TINY = b'Hello world!'
LARGE = b'x' * 65536
STREAM = b'first\nlast\n'
async def raw_app(scope, receive, send):
if scope['type'] == 'lifespan':
while True:
message = await receive()
if message['type'] == 'lifespan.startup':
await send({'type': 'lifespan.startup.complete'})
elif message['type'] == 'lifespan.shutdown':
await send({'type': 'lifespan.shutdown.complete'})
return
path = scope['path']
if path == '/tiny':
body = TINY
elif path == '/bytes':
body = LARGE
elif path == '/echo':
parts = []
while True:
message = await receive()
if message['type'] != 'http.request':
return
parts.append(message.get('body', b''))
if not message.get('more_body', False):
break
body = b''.join(parts)
elif path == '/_benchmark_pid':
body = str(os.getpid()).encode('ascii')
elif path == '/stream':
await send({'type': 'http.response.start', 'status': 200,
'headers': [(b'content-type', b'text/plain'), (b'content-length', b'11')]})
await send({'type': 'http.response.body', 'body': b'first\n', 'more_body': True})
await asyncio.sleep(0.05)
await send({'type': 'http.response.body', 'body': b'last\n'})
return
else:
await send({'type': 'http.response.start', 'status': 404})
await send({'type': 'http.response.body', 'body': b'missing'})
return
await send({'type': 'http.response.start', 'status': 200,
'headers': [(b'content-type', b'text/plain'),
(b'content-length', str(len(body)).encode('ascii'))]})
await send({'type': 'http.response.body', 'body': body})
def __getattr__(name):
if name != 'fastapi_app':
raise AttributeError(name)
from fastapi import FastAPI
app = FastAPI()
@app.get('/json')
async def json_response():
return {'hello': 'world'}
@app.get('/_benchmark_pid')
async def process_id():
return os.getpid()
globals()['fastapi_app'] = app
return app