Escreva um serviço Web básico para o App Engine

Escreva e teste localmente um serviço Web que disponibilize um ficheiro HTML estático através do Flask. Em seguida, crie os ficheiros de configuração necessários para implementar o serviço Web no App Engine.

Neste passo, cria e testa localmente uma versão de um serviço Web que apresenta dados de marcadores de posição. O objetivo aqui é garantir que o serviço Web básico está a funcionar antes de adicionar a autenticação do Firebase e do Datastore.

Antes de começar

  1. Se ainda não criou um Google Cloud projeto, crie um Google Cloud projeto.

  2. Se ainda não o fez, configure o seu ambiente local para o desenvolvimento em Python 3 concluindo o seguinte:

    • Transfira e instale o Python 3 para desenvolver o seu serviço Web e executar a CLI Google Cloud.

    • Use as suas Google Cloud credenciais de utilizador para fazer a autenticação na CLI do Google Cloud e ativar os testes locais com o Armazenamento de Dados:

      gcloud auth application-default login
      

Estruture os ficheiros de serviços Web

O diretório do projeto onde cria o seu serviço Web tem a seguinte estrutura de ficheiros:

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

As secções seguintes oferecem um exemplo de como configurar os ficheiros no diretório do projeto.

Escreva o seu serviço Web

A iteração inicial do seu serviço Web usa o Flask para publicar um modelo HTML baseado em Jinja.

Para configurar o seu serviço Web:

  1. Crie o seu ficheiro 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. Adicione comportamentos e estilos com ficheiros static/script.js e static/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. No ficheiro main.py, use o Flask para renderizar o modelo HTML com os dados de marcadores de posição:

    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. Configure todas as dependências de que precisa para o seu serviço Web no ficheiro requirements.txt:

    Flask==3.0.0
    

Teste o seu serviço Web

Teste o seu serviço Web executando-o localmente num ambiente virtual:

Mac OS / Linux

  1. Crie um ambiente Python isolado:
    python3 -m venv env
    source env/bin/activate
  2. Se não estiver no diretório que contém o código de exemplo, navegue para o diretório que contém o código de exemplo hello_world. Em seguida, instale as dependências:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. Execute a aplicação:
    python main.py
  4. No navegador de Internet, introduza o seguinte endereço:
    http://localhost:8080

Windows

Use o PowerShell para executar os seus pacotes Python.

  1. Localize a sua instalação do PowerShell.
  2. Clique com o botão direito do rato no atalho para o PowerShell e inicie-o como administrador.
  3. Crie um ambiente Python isolado.
    python -m venv env
    .\env\Scripts\activate
  4. Navegue para o diretório do projeto e instale as dependências. Se não estiver no diretório que contém o código de exemplo, navegue para o diretório que contém o hello_world código de exemplo. Em seguida, instale as dependências:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. Execute a aplicação:
    python main.py
  6. No navegador de Internet, introduza o seguinte endereço:
    http://localhost:8080

Configure o seu serviço Web para o App Engine

Para implementar o seu serviço Web no App Engine, precisa de um ficheiro app.yaml. Este ficheiro de configuração define as definições do seu serviço Web para o App Engine.

Para configurar o seu serviço Web para implementação no App Engine, crie o ficheiro app.yaml no diretório raiz do seu projeto, por exemplo, 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: python313

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

Tenha em atenção que, para este serviço Web simples, o ficheiro app.yaml tem de definir apenas a definição de tempo de execução e os controladores para ficheiros estáticos.

Para serviços Web mais complicados, pode configurar definições adicionais no seu app.yaml, como o dimensionamento, controladores adicionais e outros elementos da aplicação, como variáveis de ambiente e nomes de serviços. Para mais informações e uma lista de todos os elementos suportados, consulte a app.yaml referência.

Passos seguintes

Agora que configurou, criou e testou o seu serviço Web, pode implementar esta versão do serviço Web no App Engine.