Ale*_*der 19 python wsgi web-applications jinja2 flask
是否有Flask或Jinja2配置标志/扩展名来在渲染模板后自动缩小HTML输出?
Ham*_*FzM 27
找到了更好的方法来做到这一点.您可以使用以下方法缩小所有页面:
from flask import Flask
from htmlmin.main import minify
app = Flask(__name__)
@app.after_request
def response_minify(response):
"""
minify html response to decrease site traffic
"""
if response.content_type == u'text/html; charset=utf-8':
response.set_data(
minify(response.get_data(as_text=True))
)
return response
return response
Run Code Online (Sandbox Code Playgroud)
看看这里https://github.com/cobrateam/django-htmlmin#using-the-html_minify-function
我意识到它主要用于django但是这个例子展示了如何使用这个项目代码来做你想要的烧瓶视图,我想.
使用装饰器。
from htmlmin.decorator import htmlmin
@htmlmin
def home():
...
Run Code Online (Sandbox Code Playgroud)
或者你可以只使用:
re.sub(r'>\s+<', '><', '<tag> </tag>') # results '<tag></tag>'
Run Code Online (Sandbox Code Playgroud)
我写了一个烧瓶扩展来实现这个目的。您可以使用它进行安装,pip install flask-htmlmin源代码可在https://github.com/hamidfzm/Flask-HTMLmin 获得。希望它会很有用。
我使用以下装饰器
import bs4
import functools
import htmlmin
def prettify(route_function):
@functools.wraps(route_function)
def wrapped(*args, **kwargs):
yielded_html = route_function(*args, **kwargs)
soup = bs4.BeautifulSoup(yielded_html, 'html.parser')
return soup.prettify()
return wrapped
def uglify(route_function):
@functools.wraps(route_function)
def wrapped(*args, **kwargs):
yielded_html = route_function(*args, **kwargs)
minified_html = htmlmin.minify(yielded_html)
return minified_html
return wrapped
Run Code Online (Sandbox Code Playgroud)
并像这样简单地包装默认的 render_template 函数
if app.debug:
flask.render_template = prettify(flask.render_template)
else:
flask.render_template = uglify(flask.render_template)
Run Code Online (Sandbox Code Playgroud)
这有一个额外的好处是自动添加到缓存中,因为我们实际上并不接触 app.route
| 归档时间: |
|
| 查看次数: |
10593 次 |
| 最近记录: |