【问题标题】:Serving static HTML with Google App Engine and bottle使用 Google App Engine 和 Bottle 提供静态 HTML
【发布时间】:2015-05-28 13:02:21
【问题描述】:

我在使用带有 bottle.py 的 Google App Engine 并尝试在用户访问 / 时提供静态 HTML 文件。为此,我在我的main.py 中有这个:

bottle = Bottle()

@bottle.route('/')
def index():
    """Serve index.html."""
    return static_file('index.html', root='/static')

我的app.yaml 中也有以下内容:

handlers:
- url: /favicon\.ico
  static_files: static/favicon.ico
  upload: static/favicon\.ico
- url: /static
  static_dir: static
  application-readable: true
- url: /.*
  script: main.bottle

favicon 和 CSS 文件(都在 static 目录中)可以正常使用,尽管不直接提供。但是,转到 / 会导致 404 错误。我对bottle.route 应该做什么以及app.yaml 应该做什么有点困惑。

为了完整起见,我的目录结构如下所示:

src
+-- main.py
+-- app.yaml
+-- static
    +-- favicon.ico
    +-- index.html
    +-- stylesheet.css
+-- [other unimportant files]

【问题讨论】:

    标签: python google-app-engine bottle


    【解决方案1】:

    要在 App Engine 中提供静态文件,直接从 app.yaml 执行此操作是迄今为止最有效的(对您的用户来说更快,如果您通过免费的每日配额,对您来说更便宜)——只需添加

    - url: /
      static_files: static/index.html
    

    app.yaml “全能”url: /.* 指令之前。

    这样,您的应用将不会将该静态文件请求排在其他可能正在等待的其他请求之后,也不需要启动和预热新实例,也不需要运行您的任何代码 - 它只会提供服务静态文件pronto,就像 Google 知道的一样快(包括缓存和类似 CDN 的“幕后”加速,如果适用)。

    真的没有理由从代码中提供静态文件,因为您可以如此轻松地利用 Google 自己的服务基础架构!

    【讨论】:

    • 谢谢你,这有效。确实需要将upload: static/index.html 添加到app.yaml。启动一个实例等并没有引起我的注意。你知道的越多。
    【解决方案2】:

    下面的代码应该可以工作。

    bottle = Bottle()
    
    @bottle.route('/')
    def index():
        """Serve index.html."""
        return static_file('index.html', root=os.path.join(os.path.dirname(os.path.realpath(__file__)), "/static"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2016-09-02
      • 1970-01-01
      • 2017-10-06
      相关资源
      最近更新 更多