From d65bcbbf0aeb5419f4d1da164849054f7797f9dd Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 21 Jan 2022 00:09:39 +0200 Subject: [PATCH] Added util directory and http util file HTTP utils are anything generally useful for HTTP things, currently thats just compressing a string if its larger than a given number of bytes. These libraries are intended to be available to plugins --- util/http.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 util/http.py diff --git a/util/http.py b/util/http.py new file mode 100644 index 00000000..441ff386 --- /dev/null +++ b/util/http.py @@ -0,0 +1,24 @@ +"""Utilities for dealing with HTTP.""" +from __future__ import annotations + +from gzip import compress + +__all__ = ['gzip'] + + +def gzip(data: str | bytes, max_size: int = 512, encoding='utf-8') -> tuple[bytes, bool]: + """ + Compress the given data if the max size is greater than specified. + + :param data: The data to compress + :param max_size: The max size of data, in bytes, defaults to 512 + :param encoding: The encoding to use if data is a str, defaults to 'utf-8' + :return: the payload to send, and a bool indicating compression state + """ + if isinstance(data, str): + data = data.encode(encoding=encoding) + + if len(data) <= max_size: + return data, False + + return compress(data), True