Queer European MD passionate about IT

hacks.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. """Useful functions to patch third part libraries until they are fixed."""
  2. import aiohttp
  3. from urllib.parse import quote
  4. def hacked_content_disposition_header(disptype, quote_fields=True, **params):
  5. """Prevent aiohttp from encoding file names as URLs.
  6. Thanks @Nickoala (Nick Lee) for this hack from his archived `telepot` repo.
  7. See https://github.com/nickoala/telepot/blob/master/telepot/aio/hack.py
  8. for details.
  9. """
  10. if not disptype or not (aiohttp.helpers.TOKEN > set(disptype)):
  11. raise ValueError('bad content disposition type {!r}'
  12. ''.format(disptype))
  13. value = disptype
  14. if params:
  15. lparams = []
  16. for key, val in params.items():
  17. if not key or not (aiohttp.helpers.TOKEN > set(key)):
  18. raise ValueError('bad content disposition parameter'
  19. ' {!r}={!r}'.format(key, val))
  20. if key == 'filename':
  21. qval = val
  22. else:
  23. qval = quote(val, '') if quote_fields else val
  24. lparams.append((key, '"%s"' % qval))
  25. sparams = '; '.join('='.join(pair) for pair in lparams)
  26. value = '; '.join((value, sparams))
  27. return value