]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays...
authorabc.zxy <zxnzysj@163.com>
Fri, 2 Sep 2022 10:17:31 +0000 (18:17 +0800)
committerGitHub <noreply@github.com>
Fri, 2 Sep 2022 10:17:31 +0000 (10:17 +0000)
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>
fastapi/responses.py
tests/test_orjson_response_class.py [new file with mode: 0644]

index 6cd7931571fc9ed2b4e53839fc68f7783d58e0f4..88dba96e8f5666b0ef947b69d2adb83847b96c61 100644 (file)
@@ -31,4 +31,6 @@ class ORJSONResponse(JSONResponse):
 
     def render(self, content: Any) -> bytes:
         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
+        )
diff --git a/tests/test_orjson_response_class.py b/tests/test_orjson_response_class.py
new file mode 100644 (file)
index 0000000..6fe62da
--- /dev/null
@@ -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}