Skip to content

Instantly share code, notes, and snippets.

@wodim
Created March 31, 2018 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wodim/504d58372686a7c0676cda4854b7df71 to your computer and use it in GitHub Desktop.
Save wodim/504d58372686a7c0676cda4854b7df71 to your computer and use it in GitHub Desktop.
Flask minify after_request handler
mods = ((re.compile('[\n\r]'), ''),
(re.compile(' +'), ' '),)
@app.after_request
def mod_response(response):
if mods and response.content_type.startswith('text/html;'):
response_data = response.get_data(as_text=True)
for before, after in mods:
if isinstance(before, str): # it's a string replacement
response_data = response_data.replace(before, after)
else: # it's a re
response_data = before.sub(after, response_data)
response.set_data(response_data)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment