为 App Engine 编写基本 Web 服务

使用 Flask 编写一个可提供静态 HTML 文件的 Web 服务并在本地进行测试。 然后,创建将该 Web 服务部署到 App Engine 时所需的配置文件。

在此步骤中,您将创建一个可显示占位符数据的 Web 服务版并在本地进行测试。该操作的目标是确保您的基本 Web 服务在添加 Datastore 和 Firebase 身份验证前可正常运行。

准备工作

  1. 如果尚未创建 Google Cloud 项目,请创建一个 Google Cloud 项目

  2. 如果您还没有为 Python 3 开发设置本地环境,请完成以下操作:

    • 下载并安装 Python 3,用于开发 Web 服务和运行 Google Cloud CLI。

    • 使用 Google Cloud 用户凭据通过 Google Cloud CLI 进行身份验证,并使用 Datastore 启用本地测试:

      gcloud auth application-default login
      

设计 Web 服务文件的结构

您在其中创建 Web 服务的项目目录将具有以下文件结构:

  • building-an-app/
    • app.yaml
    • main.py
    • requirements.txt
    • static/
      • script.js
      • style.css
    • templates/
      • index.html

以下几个部分提供了一个如何在项目目录中设置文件的示例。

编写 Web 服务

Web 服务的初始迭代使用 Flask 来提供基于 Jinja 的 HTML 模板

要设置 Web 服务,请执行以下操作:

  1. 创建 templates/index.html 文件:

    <!doctype html>
    <!--
     Copyright 2021 Google LLC
    
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    -->
    
    <html>
    <head>
      <title>Datastore and Firebase Auth Example</title>
      <script src="{{ url_for('static', filename='script.js') }}"></script>
      <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
    
      <h1>Datastore and Firebase Auth Example</h1>
    
      <h2>Last 10 visits</h2>
      {% for time in times %}
        <p>{{ time }}</p>
      {% endfor %}
    
    </body>
    </html>
    
  2. 使用 static/script.jsstatic/style.css 文件添加行为和样式:

    'use strict';
    
    window.addEventListener('load', function () {
    
      console.log("Hello World!");
    
    });
    /**
     * Copyright 2021 Google LLC
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    body {
      font-family: "helvetica", sans-serif;
      text-align: center;
    }
    
  3. main.py 文件中,使用 Flask 呈现包含占位符数据的 HTML 模板:

    import datetime
    
    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    
    @app.route("/")
    def root():
        # For the sake of example, use static information to inflate the template.
        # This will be replaced with real information in later steps.
        dummy_times = [
            datetime.datetime(2018, 1, 1, 10, 0, 0),
            datetime.datetime(2018, 1, 2, 10, 30, 0),
            datetime.datetime(2018, 1, 3, 11, 0, 0),
        ]
    
        return render_template("index.html", times=dummy_times)
    
    
    if __name__ == "__main__":
        # This is used when running locally only. When deploying to Google App
        # Engine, a webserver process such as Gunicorn will serve the app. This
        # can be configured by adding an `entrypoint` to app.yaml.
        # Flask's development server will automatically serve static files in
        # the "static" directory. See:
        # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
        # App Engine itself will serve those files as configured in app.yaml.
        app.run(host="127.0.0.1", port=8080, debug=True)
  4. requirements.txt 文件中配置 Web 服务所需的所有依赖项:

    Flask==3.0.0
    

测试 Web 服务

通过在虚拟环境中本地运行 Web 服务来对其进行测试:

Mac OS/Linux

  1. 创建一个独立的 Python 环境
    python3 -m venv env
    source env/bin/activate
  2. 如果您当前不在包含示例代码的目录中,则导航到包含 hello_world 示例代码的目录。然后安装依赖项:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. 运行应用:
    python main.py
  4. 在网络浏览器中,输入以下地址:
    http://localhost:8080

Windows

使用 Powershell 运行 Python 包。

  1. 找到已安装的 PowerShell
  2. 右键点击 Powershell 的快捷方式,并以管理员身份启动。
  3. 创建一个独立的 Python 环境
    python -m venv env
    .\env\Scripts\activate
  4. 导航到项目目录并安装依赖项。如果您当前不在包含示例代码的目录中,则导航到包含 hello_world 示例代码的目录。然后安装依赖项:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. 运行应用:
    python main.py
  6. 在网络浏览器中,输入以下地址:
    http://localhost:8080

为 App Engine 配置 Web 服务

要将 Web 服务部署到 App Engine,您需要一个 app.yaml 文件。 此配置文件定义了 App Engine 的 Web 服务设置。

要配置 Web 服务以便部署到 App Engine,请在项目的根目录中创建 app.yaml 文件,例如 building-an-app

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

请注意,在这个简单的 Web 服务中,您的 app.yaml 文件只需定义静态文件的运行时设置和处理程序。

对于更复杂的 Web 服务,您可以在 app.yaml 中配置其他设置,例如扩缩、其他处理程序及其他应用元素(如环境变量和服务名称)。如需了解详情和所有受支持元素的列表,请参阅 app.yaml 参考

后续步骤

现在您已配置、创建并测试 Web 服务,接下来即可将该版本的 Web 服务部署到 App Engine。