peterbe / premailer

Turns CSS blocks into style attributes
https://premailer.io
BSD 3-Clause "New" or "Revised" License
1.06k stars 188 forks source link

Add cache support for _load_external_url #256

Closed thenewguy closed 2 years ago

thenewguy commented 3 years ago

It would be handy if one could use allow_network to fetch styles and also rely on a cache for speedy results

It might be simple enough to just expose the session creation used for requests. Then something like CacheControl could be dropped in as a simple fix or something more advanced like a custom cache wrapper if needed.

thenewguy commented 3 years ago

Would you accept a PR here? The idea is to make the request session a property on the Premailer instance. It would default to requests as used now. The session argument passed to the constructor would take precedence.

This would allow for caching without requiring Premailer to be opinionated about how it happens

peterbe commented 3 years ago

I'd love a PR. But would you mind making it more a "plugin"? The default plugin, could be requests. E.g.

import requests
from premailer import transform

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

print(transform(html_string, session=s))

Then, if you want retry support you just create another session. Because any requests session has a get function and that's all you need. So in your case, you can, if you so prefer to combine CacheControl with requests you pass that in.

Yeah, I'd be happy to review a PR. Don't forget to update the README too.