PythonFlask不更新图像

2024-05-20 22:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一些关于图片的问题,但没有一个能解决我的问题。我有一个应用程序,可以创建一个图像,保存它,然后显示它。一次。它应该多次执行此操作(每次更改图像时,它都应该加载一个新图像)。它不显示;它只显示与其显示的文件名关联的第一个图像。这些文件不再在静态文件夹中,而是显示在应用程序中。

创建图像,并通过以下方式保存到静态文件夹的子文件夹中:

img.save('../source/static/images/characters/{}.png'
              .format(self.char.name), "PNG")

应用程序通过以下方式加载:

'<img src="/static/images/characters/{}.png" '
            .format(self.name) +
            ' alt="{}" title="{}" '.format(self.name, self.name) +
            'width=100% />'

(通过代码操作添加到烧瓶应用程序中)。

问题是我有两个测试用例:一个是文本出现在图像上(添加的文本在代码的几次迭代前被删除),另一个是alpha通道位于错误的位置(RGBA->;ARGB问题,已解决,但我在站点上看不到新文件)。目前,仅在本地运行/测试。正确的图片出现在~\source\static\images\characters中。所有*.py文件都在源代码中。我需要做什么才能解决这个问题?

我试过:

@app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response

作为我的app.py文件末尾的一段单独代码,还尝试添加:

app.config["CACHE_TYPE"] = "null"

到调用创建图像的页的app.route()开头。

另一个可能的注意事项是,图像应该在一个表中,但似乎不是。。。我的意思是,有一个带标题的表,然后一个列中有一个表,另一个列中有图像。。。但是第一列的文本在图像的下方(尽管每一列都在各自的适当位置)。奇怪,但可能无关。

那么,为什么烧瓶不能正确更新,我该如何强制它更新呢?(关闭并重新打开程序时问题仍然存在)。

更新: 这似乎起作用了。。。

Using Flask, how do I modify the Cache-Control header for ALL output?

通过添加:

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1

到顶部(包括app=Flask部分以帮助其他新手),最后:

# No caching at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    if 'Cache-Control' not in response.headers:
        response.headers['Cache-Control'] = 'no-store'
    return response

但只对单个实例有效,其他实例的缓存仍然很奇怪。可以从以前缓存,而另一个刚刚超时,但这不应该发生,因为我一直关闭服务器(localhost),对吧?


Tags: 文件name图像self文件夹app应用程序format
2条回答

这似乎管用

Using Flask, how do I modify the Cache-Control header for ALL output?

通过添加:

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

到顶部(包括app=Flask部分以帮助其他新手),最后:

# No caching at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    response.headers['Cache-Control'] = 'no-store, no-cache, must-
    revalidate, post-check=0, pre-check=0, max-age=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '-1'
    return response

这是可行的,但是我的命令提示符窗口中的日志会不断地发送信息。

尝试更改图像名称,以便每次重新生成图像时,它看起来都是一个新图像。您可以使用文件名的一些基于时间的后缀。或者您可以更改图像的url,为其添加一些伪get参数。

参考: flask cache busting

flask cache busting library

相关问题 更多 >