python273 / telegraph

Telegraph API wrapper | Telegra.ph
https://pypi.org/project/telegraph/
MIT License
287 stars 43 forks source link

Significantly reduce size of payload #48

Open mercuree opened 1 year ago

mercuree commented 1 year ago

When creating telegraph page, by default requests.post is sending data with 'Content-type': 'application/x-www-form-urlencoded'

It's huge, because json payload is percent-encoded, for example this dict (43 bytes): {"key": "value with non-ascii: абвгд"} looks like this when sending request (97 bytes): %7B%22key%22%3A%20%22value%20with%20non-ascii%3A%20%5Cu0430%5Cu0431%5Cu0432%5Cu0433%5Cu0434%22%7D

Telegra.ph accepts 'Content-Type': 'application/json' header and you can use this feature instead to avoid percent-encoding.

  1. Use 'Content-Type': 'application/json' instead of default percent-encoding
  2. Use json.dumps(data, ensure_ascii=False). Telegra.ph accepts utf-8 and no need to escape into \uXXXX for non-ascii characters.
  3. Use separators without spaces json.dumps(data, ensure_ascii=False, separators=(',', ':'))
  4. Also you don't need to separately convert content property to string, it can be sent like regular json

Unfortunately, this will not help to put more than 64 kb on a page, it helps only for reducing network overhead.