| 1 |
## Compression with gRPC Python |
| 2 |
|
| 3 |
gRPC offers lossless compression options in order to decrease the number of bits |
| 4 |
transferred over the wire. Three levels of compression are available: |
| 5 |
|
| 6 |
- `grpc.Compression.NoCompression` - No compression is applied to the payload. (default) |
| 7 |
- `grpc.Compression.Deflate` - The "Deflate" algorithm is applied to the payload. |
| 8 |
- `grpc.Compression.Gzip` - The Gzip algorithm is applied to the payload. |
| 9 |
|
| 10 |
The default option on both clients and servers is `grpc.Compression.NoCompression`. |
| 11 |
|
| 12 |
See [the gRPC Compression Spec](https://github.com/grpc/grpc/blob/master/doc/compression.md) |
| 13 |
for more information. |
| 14 |
|
| 15 |
### Client Side Compression |
| 16 |
|
| 17 |
Compression may be set at two levels on the client side. |
| 18 |
|
| 19 |
#### At the channel level |
| 20 |
|
| 21 |
```python |
| 22 |
with grpc.insecure_channel('foo.bar:1234', compression=grpc.Compression.Gzip) as channel: |
| 23 |
use_channel(channel) |
| 24 |
``` |
| 25 |
|
| 26 |
#### At the call level |
| 27 |
|
| 28 |
Setting the compression method at the call level will override any settings on |
| 29 |
the channel level. |
| 30 |
|
| 31 |
```python |
| 32 |
stub = helloworld_pb2_grpc.GreeterStub(channel) |
| 33 |
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), |
| 34 |
compression=grpc.Compression.Deflate) |
| 35 |
``` |
| 36 |
|
| 37 |
|
| 38 |
### Server Side Compression |
| 39 |
|
| 40 |
Additionally, compression may be set at two levels on the server side. |
| 41 |
|
| 42 |
#### On the entire server |
| 43 |
|
| 44 |
```python |
| 45 |
server = grpc.server(futures.ThreadPoolExecutor(), |
| 46 |
compression=grpc.Compression.Gzip) |
| 47 |
``` |
| 48 |
|
| 49 |
#### For an individual RPC |
| 50 |
|
| 51 |
```python |
| 52 |
def SayHello(self, request, context): |
| 53 |
context.set_response_compression(grpc.Compression.NoCompression) |
| 54 |
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
| 55 |
``` |
| 56 |
|
| 57 |
Setting the compression method for an individual RPC will override any setting |
| 58 |
supplied at server creation time. |