我正在尝试将 CSS 媒体查询与 Jinja 和 Flask 结合使用来确定设备类型并根据设备提供适当大小的图像。来自手机的请求将获得比台式机、平板电脑等更小的图像。
问题是 {{ post|get_image(post, 480) }}
的评估独立于媒体查询,因此触发了每个实例的 get_image
自定义模板过滤器. get_image
也是为设备呈现正确图像的地方,因此多次调用(也许是不必要的调用)会对性能产生负面影响。
理想情况下,一次调用 get_image
只会执行一次媒体查询,但挑战在于媒体查询和 Jinja 完全独立,因为两者之间一无所知。
我非常感谢替代方法或建议来改进我的方法。提前致谢!
这是媒体查询的一个例子:
@media only screen and (max-device-width: 480px) {
.post {
background: url("{{ post|get_image(post, 480) }}") no-repeat center center fixed;
}
}
@media only screen and (max-device-width: 1224px) {
.post {
background: url("{{ post|get_image(post, 1224) }}") no-repeat center center fixed;
}
}
最佳答案
将您的设置更改为如下所示:
.post {
background: none no-repeat center center fixed;
}
@media only screen and (max-device-width: 480px) {
.post {
background-image: url("{{ get_image_url(post, 480) }}");
}
}
@media only screen and (max-device-width: 1224px) {
.post {
background-image: url("{{ get_image_url(post, 1224) }}");
}
}
您生成的 URL 可能如下所示:
/posts/<int:post_id>/background?s=NNNN
然后,设置代理服务器以从缓存目录中提供此类图像,如果图像不存在,则将它们转发到图像生成 Controller :
# Fake server configuration
# for no server known to man
location /posts/(:post-id:\d+)/background {
try_files /cache/:post-id:_\d+\.png or @flask-server
}
最后,在您的 Flask Controller 中生成图像,将其保存到您的缓存目录,并将其返回给请求者:
@app.route("/posts/<int:post_id>/background")
def generate_image(post_id):
# Assume that if we got here the image does not yet exist
dimensions = int(request.args.get("s", 800), 10)
image_data = generate_image(post_id, dimensions)
image_name = "{}_{}.png".format(post_id, dimensions)
image_path = os.path.join("/cache", image_name)
with open(image_path, "wb") as image:
image.write(image_data)
return Response(image_data, content_type="image/png")
如果图像生成部分成本太高,甚至无法考虑在 Controller 中执行,您可以返回 204 No-Content 并将 Cache-Control 设置为 private 并在过去设置 Expires 并将图像生成任务放入 out-of -进程队列。然后只需在您的 JavaScript 代码中轮询该端点,直到图像准备好由您的代理服务器提供服务。
关于python - 使用 CSS 媒体查询和 Flask/Jinja 进行设备检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467536/