Custom json serializers for the Starlette web framework.
Project description
Starlette Json
Introduction
Starlette json responses for various json serializers available in the python community.
Why:
- Remove
ujson
dependency from core starlette package - Add adaptors for other serializers
- Customize serializer rendering settings
Requirements
- Python 3.6+
- Starlette
Installation
$ pip install starlette-json
Optional installs
Install at least one of these:
- orjson
pip install orjson
- Ultrajson
pip install ujson
- Rapidjson
pip install python-rapidjson
- SimpleJson
pip install simplejson
Usage
Response examples
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette_json import ORJsonResponse, UJsonResponse, RapidJsonResponse, SimpleJsonResponse
app = Starlette()
data = {'Hello': 'World'}
@app.route('/json')
def json(request):
return JSONResponse(data)
@app.route('/orjson')
def orjson(request):
return ORJsonResponse(data)
@app.route('/ujson')
def ujson(request):
return UJsonResponse(data)
@app.route('/rapidjson')
def rapidjson(request):
return RapidJsonResponse(data)
@app.route('/simplejson')
def rapidjson(request):
return SimpleJsonResponse(data)
Custom response rendering options:
See the docs for the specific json serializer for available options
from starlette.applications import Starlette
from starlette_json import ORJsonResponse, UJsonResponse, RapidJsonResponse
import orjson
app = Starlette()
data = {'Hello': 'World'}
@app.route('/orjson')
def orjson(request):
return ORJsonResponse(
data,
default=lambda x: str(x),
option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC
)
@app.route('/ujson')
def ujson(request):
return UJsonResponse(
data,
encode_html_chars=True,
ensure_ascii=False,
escape_forward_slashes=False
)
@app.route('/rapidjson')
def rapidjson(request):
return RapidJsonResponse(data, sort_keys=True, indent=4)
@app.route('/simplejson')
def rapidjson(request):
return SimpleJsonResponse(
data,
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True
)
Json request body parsing:
from starlette.applications import Starlette
from starlette_json import ORJsonMiddleware, ORJsonResponse
app = Starlette()
app.add_middleware(ORJsonMiddleware)
@app.route('/orjson')
def orjson(request):
body = await request.json() # Parsed with orjson
return ORJsonResponse({'message':'ok'})
Contributing
PRs very welcome. CONTRIBUTING.md
Todo
- Tests?
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for starlette_json-19.11.12-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8b94e6b5e1bde8e34a883e98ef799ac3ed6fa17a2709a02be66957e81c8acef1 |
|
MD5 | dd16abe905fe1fc8c8a0a383eeab1e92 |
|
BLAKE2b-256 | 58a460445927166ad94c7bb56d58d3cb1230798bbfa66ef61d00ce06500f6977 |