|
@@ -3,7 +3,7 @@ import asyncpg
|
|
|
import os
|
|
|
import jinja2
|
|
|
from fastapi import FastAPI
|
|
|
-from starlette.responses import HTMLResponse, UJSONResponse, PlainTextResponse
|
|
|
+from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse
|
|
|
from random import randint
|
|
|
from operator import itemgetter
|
|
|
from urllib.parse import parse_qs
|
|
@@ -14,6 +14,19 @@ WRITE_ROW_SQL = 'UPDATE "world" SET "randomnumber"=$1 WHERE id=$2'
|
|
|
ADDITIONAL_ROW = [0, 'Additional fortune added at request time.']
|
|
|
|
|
|
|
|
|
+# https://www.starlette.io/responses/#custom-json-serialization
|
|
|
+try:
|
|
|
+ import orjson
|
|
|
+
|
|
|
+ class CustomJSONResponse(JSONResponse):
|
|
|
+ def render(self, content):
|
|
|
+ return orjson.dumps(content)
|
|
|
+
|
|
|
+except ImportError:
|
|
|
+
|
|
|
+ class CustomJSONResponse(JSONResponse):
|
|
|
+ pass
|
|
|
+
|
|
|
|
|
|
async def setup_database():
|
|
|
global connection_pool
|
|
@@ -58,7 +71,7 @@ app = FastAPI()
|
|
|
|
|
|
@app.get('/json')
|
|
|
async def json_serialization():
|
|
|
- return UJSONResponse({'message': 'Hello, world!'})
|
|
|
+ return CustomJSONResponse({'message': 'Hello, world!'})
|
|
|
|
|
|
|
|
|
@app.get('/db')
|
|
@@ -68,7 +81,7 @@ async def single_database_query():
|
|
|
async with connection_pool.acquire() as connection:
|
|
|
number = await connection.fetchval(READ_ROW_SQL, row_id)
|
|
|
|
|
|
- return UJSONResponse({'id': row_id, 'randomNumber': number})
|
|
|
+ return CustomJSONResponse({'id': row_id, 'randomNumber': number})
|
|
|
|
|
|
|
|
|
@app.get('/queries')
|
|
@@ -84,7 +97,7 @@ async def multiple_database_queries(queries = None):
|
|
|
number = await statement.fetchval(row_id)
|
|
|
worlds.append({'id': row_id, 'randomNumber': number})
|
|
|
|
|
|
- return UJSONResponse(worlds)
|
|
|
+ return CustomJSONResponse(worlds)
|
|
|
|
|
|
|
|
|
@app.get('/fortunes')
|
|
@@ -110,7 +123,7 @@ async def database_updates(queries = None):
|
|
|
await statement.fetchval(row_id)
|
|
|
await connection.executemany(WRITE_ROW_SQL, updates)
|
|
|
|
|
|
- return UJSONResponse(worlds)
|
|
|
+ return CustomJSONResponse(worlds)
|
|
|
|
|
|
|
|
|
@app.get('/plaintext')
|