All Projects → florimondmanca → msgpack-asgi

florimondmanca / msgpack-asgi

Licence: MIT license
Drop-in MessagePack support for ASGI applications and frameworks

Programming Languages

python
139335 projects - #7 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to msgpack-asgi

inboard
🚢 Docker images and utilities to power your Python APIs and help you ship faster. With support for Uvicorn, Gunicorn, Starlette, and FastAPI.
Stars: ✭ 106 (+6%)
Mutual labels:  asgi, starlette, fastapi
arel
Lightweight browser hot reload for Python ASGI web apps
Stars: ✭ 69 (-31%)
Mutual labels:  asgi, starlette, fastapi
fastapi-zeit-now
A simple example of deploying FastAPI as a Zeit Serverless Function
Stars: ✭ 24 (-76%)
Mutual labels:  asgi, starlette, fastapi
serverless-mangum-examples
Example ASGI applications and Serverless Framework configurations using Mangum
Stars: ✭ 26 (-74%)
Mutual labels:  asgi, starlette, fastapi
starlette-graphene3
An ASGI app for using Graphene v3 with Starlette / FastAPI
Stars: ✭ 52 (-48%)
Mutual labels:  asgi, starlette, fastapi
starlite
Light, Flexible and Extensible ASGI API framework
Stars: ✭ 1,525 (+1425%)
Mutual labels:  asgi, starlette
TikTokDownloader PyWebIO
🚀「Douyin_TikTok_Download_API」是一个开箱即用的高性能异步抖音|TikTok数据爬取工具,支持API调用,在线批量解析及下载。
Stars: ✭ 919 (+819%)
Mutual labels:  asgi, fastapi
msgpack-perl
MessagePack serializer implementation for Perl / msgpack.org[Perl]
Stars: ✭ 48 (-52%)
Mutual labels:  msgpack, messagepack
fastapi-websocket-broadcast
Websocket 'broadcast' demo using FastAPI/Starlette
Stars: ✭ 106 (+6%)
Mutual labels:  starlette, fastapi
morelia server
Server for MoreliaTalk network
Stars: ✭ 25 (-75%)
Mutual labels:  starlette, fastapi
rcppmsgpack
MsgPack Headers for R / msgpack.org[R]
Stars: ✭ 17 (-83%)
Mutual labels:  msgpack, messagepack
what-the-pack
Ultra-fast MessagePack for NodeJS & Browsers | msgpack.org[Javascript/NodeJS]
Stars: ✭ 36 (-64%)
Mutual labels:  msgpack, messagepack
async-asgi-testclient
A framework-agnostic library for testing ASGI web applications
Stars: ✭ 123 (+23%)
Mutual labels:  asgi, starlette
fastapi-project
FastAPI application without global variables(almost) =)
Stars: ✭ 26 (-74%)
Mutual labels:  asgi, fastapi
starlette-opentracing
Opentracing support for Starlette and FastApi
Stars: ✭ 62 (-38%)
Mutual labels:  starlette, fastapi
mongox
Familiar async Python MongoDB ODM
Stars: ✭ 113 (+13%)
Mutual labels:  asgi, starlette
fastAPI-aiohttp-example
How to use and test fastAPI with an aiohttp client
Stars: ✭ 69 (-31%)
Mutual labels:  asgi, fastapi
restish
Restish is a CLI for interacting with REST-ish HTTP APIs with some nice features built-in
Stars: ✭ 453 (+353%)
Mutual labels:  msgpack, fastapi
starlette-context
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.
Stars: ✭ 320 (+220%)
Mutual labels:  starlette, fastapi
fastapi-azure-auth
Easy and secure implementation of Azure AD for your FastAPI APIs 🔒 B2C, single- and multi-tenant support.
Stars: ✭ 174 (+74%)
Mutual labels:  asgi, fastapi

msgpack-asgi

Build Status Coverage Package version

msgpack-asgi allows you to add automatic MessagePack content negotiation to ASGI applications (Starlette, FastAPI, Quart, etc.), with a single line of code:

app.add_middleware(MessagePackMiddleware)

(You may want to adapt this snippet to your framework-specific middleware API.)

This gives you the bandwitdth usage reduction benefits of MessagePack without having to change existing code.

Note: this comes at a CPU usage cost, since MessagePackMiddleware will perform MsgPack decoding while your application continues to decode and encode JSON data (see also How it works). If your use case is CPU-sensitive, rather than strictly focused on reducing network bandwidth, this package may not be for you.

Installation

Install with pip:

pip install "msgpack-asgi==1.*"

Quickstart

First, you'll need an ASGI application. Let's use this sample application, which exposes an endpoint that returns JSON data:

# For convenience, we use some ASGI components from Starlette.
# Install with: `$ pip install starlette`.
from starlette.requests import Request
from starlette.responses import JSONResponse


async def get_response(request):
    if request.method == "POST":
        data = await request.json()
        return JSONResponse({"data": data}, status_code=201)
    else:
        return JSONResponse({"message": "Hello, msgpack!"})


async def app(scope, receive, send):
    assert scope["type"] == "http"
    request = Request(scope=scope, receive=receive)
    response = await get_response(request)
    await response(scope, receive, send)

Then, wrap your application around MessagePackMiddleware:

from msgpack_asgi import MessagePackMiddleware

app = MessagePackMiddleware(app)

Serve your application using an ASGI server, for example with Uvicorn:

uvicorn app:app

Now, let's make a request that accepts MessagePack data in response:

curl -i http://localhost:8000 -H "Accept: application/x-msgpack"

You should get the following output:

HTTP/1.1 200 OK
date: Fri, 01 Nov 2019 17:40:14 GMT
server: uvicorn
content-length: 25
content-type: application/x-msgpack

��message�Hello, msgpack!

What happened? Since we told the application that we accepted MessagePack-encoded responses, msgpack-asgi automatically converted the JSON data returned by the Starlette application to MessagePack.

We can make sure the response contains valid MessagePack data by making the request again in Python, and decoding the response content:

>>> import requests
>>> import msgpack
>>> url = "http://localhost:8000"
>>> headers = {"accept": "application/x-msgpack"}
>>> r = requests.get(url, headers=headers)
>>> r.content
b'\x81\xa7message\xafHello, msgpack!'
>>> msgpack.unpackb(r.content, raw=False)
{'message': 'Hello, msgpack!'}

msgpack-asgi also works in reverse: it will automatically decode MessagePack-encoded data sent by the client to JSON. We can try this out by making a POST request to our sample application with a MessagePack-encoded body:

>>> import requests
>>> import msgpack
>>> url = "http://localhost:8000"
>>> data = msgpack.packb({"message": "Hi, there!"})
>>> headers = {"content-type": "application/x-msgpack"}
>>> r = requests.post(url, data=data, headers=headers)
>>> r.json()
{'data': {'message': 'Hi, there!'}}

That's all there is to it! You can now go reduce the size of your payloads.

Advanced usage

Custom implementations

msgpack-asgi supports customizing the default encoding/decoding implementation. This is useful for fine-tuning application performance via an alternative msgpack implementation for encoding, decoding, or both.

To do so, use the following arguments:

  • packb - (Optional, type: (obj: Any) -> bytes, default: msgpack.packb) - Used to encode outgoing data.
  • unpackb - (Optional, type: (data: bytes) -> Any, default: msgpack.unpackb) - Used to decode incoming data.

For example, to use the ormsgpack library for encoding:

import ormsgpack  # Installed separately.
from msgpack_asgi import MessagePackMiddleware

def packb(obj):
    option = ...  # See `ormsgpack` options.
    return ormsgpack.packb(obj, option=option)

app = MessagePackMiddleware(..., packb=packb)

Limitations

msgpack-asgi does not support request or response streaming. This is because the full request and response body content has to be loaded in memory before it can be re-encoded.

How it works

An ASGI application wrapped around MessagePackMiddleware will perform automatic content negotiation based on the client's capabilities. More precisely:

  • If the client sends MessagePack-encoded data with the application/x-msgpack content type, msgpack-asgi will automatically re-encode the body to JSON and re-write the request Content-Type to application/json for your application to consume. (Note: this means applications will not be able to distinguish between MessagePack and JSON client requests.)
  • If the client sent the Accept: application/x-msgpack header, msgpack-asgi will automatically re-encode any JSON response data to MessagePack for the client to consume.

(In other cases, msgpack-asgi won't intervene at all.)

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].