Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays (#3892)

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
abc.zxy 2022-09-02 18:17:31 +08:00 committed by GitHub
parent 173b891603
commit 7250c194da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 1 deletions

View File

@ -31,4 +31,6 @@ class ORJSONResponse(JSONResponse):
def render(self, content: Any) -> bytes: def render(self, content: Any) -> bytes:
assert orjson is not None, "orjson must be installed to use ORJSONResponse" assert orjson is not None, "orjson must be installed to use ORJSONResponse"
return orjson.dumps(content) return orjson.dumps(
content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
)

View File

@ -0,0 +1,21 @@
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from fastapi.testclient import TestClient
from sqlalchemy.sql.elements import quoted_name
app = FastAPI(default_response_class=ORJSONResponse)
@app.get("/orjson_non_str_keys")
def get_orjson_non_str_keys():
key = quoted_name(value="msg", quote=False)
return {key: "Hello World", 1: 1}
client = TestClient(app)
def test_orjson_non_str_keys():
with client:
response = client.get("/orjson_non_str_keys")
assert response.json() == {"msg": "Hello World", "1": 1}