Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ORJSONResponse #870

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ Starlette does not have any hard dependencies, but the following are optional:
* [`pyyaml`][pyyaml] - Required for `SchemaGenerator` support.
* [`graphene`][graphene] - Required for `GraphQLApp` support.
* [`ujson`][ujson] - Required if you want to use `UJSONResponse`.
* [`orjson`][orjson] - Required if you want to use `ORJSONResponse`.

You can install all of these with `pip3 install starlette[full]`.

Expand Down
19 changes: 19 additions & 0 deletions docs/responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,25 @@ async def app(scope, receive, send):
await response(scope, receive, send)
```

### ORJSONResponse

Another JSON response class that uses the optimised `orjson` library for serialisation.

`orjson` is a fast, correct JSON library for Python. It
[benchmarks](https://github.com/ijl/orjson#performance) as the fastest Python
library for JSON and is more correct than the standard json library or other
third-party libraries.

```python
from starlette.responses import ORJSONResponse


async def app(scope, receive, send):
assert scope['type'] == 'http'
response = ORJSONResponse({'hello': 'world'})
await response(scope, receive, send)
```

### RedirectResponse

Returns an HTTP redirect. Uses a 307 status code by default.
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ python-multipart
pyyaml
requests
ujson
orjson

# Testing
autoflake
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def get_packages(package):
"pyyaml",
"requests",
"ujson",
"orjson",
]
},
classifiers=[
Expand Down
13 changes: 13 additions & 0 deletions starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
except ImportError: # pragma: nocover
ujson = None # type: ignore

try:
import orjson
except ImportError: # pragma: nocover
orjson = None # type: ignore


class Response:
media_type = None
Expand Down Expand Up @@ -171,6 +176,14 @@ def render(self, content: typing.Any) -> bytes:
return ujson.dumps(content, ensure_ascii=False).encode("utf-8")


class ORJSONResponse(JSONResponse):
media_type = "application/json"

def render(self, content: typing.Any) -> bytes:
assert orjson is not None, "orjson must be installed to use ORJSONResponse"
return orjson.dumps(content)


class RedirectResponse(Response):
def __init__(
self, url: typing.Union[str, URL], status_code: int = 307, headers: dict = None
Expand Down
11 changes: 11 additions & 0 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
Response,
StreamingResponse,
UJSONResponse,
ORJSONResponse,
)
from starlette.testclient import TestClient

Expand Down Expand Up @@ -47,6 +48,16 @@ async def app(scope, receive, send):
assert response.json() == {"hello": "world"}


def test_orjson_response():
async def app(scope, receive, send):
response = ORJSONResponse({"hello": "world"})
await response(scope, receive, send)

client = TestClient(app)
response = client.get("/")
assert response.json() == {"hello": "world"}


def test_json_none_response():
async def app(scope, receive, send):
response = JSONResponse(None)
Expand Down