Como gravar um serviço da Web básico para o App Engine

Use o Flask para gravar e testar localmente um serviço da Web que disponibilize um arquivo HTML estático. Em seguida, crie os arquivos de configuração necessários para implantar o serviço da Web no App Engine.

Nesta etapa, você cria e testa localmente uma versão de um serviço da Web que exibe dados de marcadores. O objetivo aqui é garantir que seu serviço da Web básico esteja funcionando antes de adicionar a autenticação do Datastore e do Firebase.

Antes de começar

  1. Crie um projeto do Google Cloud se ainda não tiver feito isso.

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

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

    • Use suas credenciais de usuário do Google Cloud para fazer a autenticação com a Google Cloud CLI e ativar os testes locais com o Datastore:

      gcloud auth application-default login
      

Como estruturar os arquivos de serviço da Web

O diretório do projeto em que o serviço da Web é criado terá a seguinte estrutura de arquivos:

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

As seções a seguir mostram um exemplo de como configurar os arquivos no diretório do projeto.

Como gravar serviços da Web

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

Para configurar o serviço da Web:

  1. Crie seu arquivo 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 os arquivos 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 arquivo main.py, use o Flask para renderizar o modelo HTML com os dados do marcador:

    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 necessárias para seu serviço da Web no arquivo requirements.txt:

    Flask==3.0.0
    

Como testar o serviço da Web

Teste seu serviço da Web executando-o localmente em um ambiente virtual:

Mac OS/Linux

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

Windows

Use o PowerShell para executar os pacotes Python.

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

Como configurar o serviço da Web para o App Engine

Para implantar o serviço da Web no App Engine, você precisa de um arquivo app.yaml. Esse arquivo de configuração define as configurações do serviço da Web para o Google App Engine.

Para configurar o serviço da Web para implantação no App Engine, crie o arquivo app.yaml no diretório raiz do 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: 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

Observe que, para esse serviço da Web simples, seu arquivo app.yaml precisa definir apenas a configuração do ambiente de execução e os gerenciadores de arquivos estáticos.

Para serviços da Web mais complexos, é possível definir mais configurações no app.yaml, como escalonamento, outros gerenciadores e outros elementos de aplicativo, como variáveis de ambiente e nomes de serviço. Para mais informações e uma lista de todos os elementos compatíveis, consulte a referência de app.yaml.

A seguir

Agora que o serviço da Web está configurado, criado e testado, é possível implantar no App Engine essa versão do serviço da Web.