我已经使用Python和Flask成功地将一个网站部署到Google App Engine上,但首次加载页面时,性能似乎相当慢。我读到在云存储上托管一些静态文件可能会对此有所帮助,但我似乎无法让它工作。 (www.example.com仅用于说明目的)
下面是app.yaml文件:
runtime: python27
api_version: 1
threadsafe: true
automatic_scaling:
max_idle_instances: 2
handlers:
- url: /.*
script: main.app
env_variables:
CLOUD_STORAGE_BUCKET: www.example.com\static
builtins:
- deferred: on
我还创建了一个名为 www.example.com 的 Cloud Storage 存储桶,其中包含一个静态文件夹。我不知道是否需要更改 jinja2 模板中的 url_for('static') 或需要做什么来解决此问题。我不在乎上传到云存储,只是想从那里指向我的网站资源。
如有任何帮助,我们将不胜感激。顺便说一下,这是标准环境而不是弹性环境。
假设您不固定使用云存储,但很乐意使用 Google App Engine 的内置静态文件服务功能,您可以像这样编写您的
app.yaml
文件...
runtime: python39
handlers:
# This configures Google App Engine to serve the files in the app's static
# directory.
- url: /static
static_dir: static
# This handler routes all requests not caught above to your main app. It is
# required when static routes are defined, but can be omitted (along with
# the entire handlers section) when there are no static files defined.
- url: /.*
script: auto
(注意,由于原来的问题已经存在多年了,我已经更新了 Python 的版本,并省略了一些 OP 的示例设置,这些设置对于本示例的工作来说不是必需的。)
我一直在尝试使用 Google(和 @Peter W)推荐的方法,但我发现 Flask static 非常慢。我确实尝试强制缓存文件,但 Chrome(或任何人)拒绝缓存它们。我的 Docker 配置是
- url: /static
static_dir: application/static
http_headers:
Cache-Control: "public, max-age=84000"
加载一个小的 CSS 文件需要 3-4 秒。相反,我将静态文件复制到云存储,而不是调用“静态”,我只是链接到 href,文件现在有 100 毫秒。它们仍然没有被缓存,这很烦人,但这是一个不同的问题。