Escribe un servicio web básico para App Engine

Escribe y prueba de forma local un servicio web que entregue un archivo HTML estático con Flask. Luego, crea los archivos de configuración que necesitas para implementar el servicio web en App Engine.

En este paso, crearás y probarás localmente una versión de un servicio web que muestra datos de marcador de posición. El objetivo aquí es garantizar que el servicio web básico esté funcionando antes de agregar la autenticación de Datastore y Firebase.

Antes de comenzar

  1. Si aún no creaste un proyecto de Google Cloud, crea uno.

  2. Si aún no lo has hecho, configura tu entorno local para el desarrollo con Python 3 de la siguiente manera:

    • Descarga y, luego, instala Python 3 para desarrollar tu servicio web y ejecutar Google Cloud CLI.

    • Usa tus credenciales de usuario de Google Cloud para autenticarte con Google Cloud CLI y habilitar las pruebas locales con Datastore:

      gcloud auth application-default login
      

Estructura los archivos del servicio web

El directorio del proyecto donde crees tu servicio web tendrá la siguiente estructura de archivos:

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

En las siguientes secciones, se proporciona un ejemplo de cómo configurar los archivos en el directorio de tu proyecto.

Escribe tu servicio web

La iteración inicial de tu servicio web utiliza Flask a fin de entregar una plantilla HTML basada en Jinja.

Para configurar tu servicio web, sigue estos pasos:

  1. Crea tu archivo 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. Agrega comportamientos y estilos con los archivos static/script.js y 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. En tu archivo main.py, utiliza Flask para generar la plantilla HTML con los datos del marcador de posición:

    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. Configura todas las dependencias que necesitarás para el servicio web en tu archivo requirements.txt:

    Flask==3.0.0
    

Prueba tu servicio web

Prueba tu servicio web mediante su ejecución local en un entorno virtual:

macOS/Linux

  1. Crea un entorno aislado de Python:
    python3 -m venv env
    source env/bin/activate
  2. Si no estás en el directorio que contiene el código de muestra, navega al directorio que contiene el código de muestra hello_world. Luego, instala las dependencias:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. Ejecute la aplicación:
    python main.py
  4. En el navegador web, ingresa la siguiente dirección:
    http://localhost:8080

Windows

Usa PowerShell para ejecutar tus paquetes de Python.

  1. Ubica la instalación de PowerShell.
  2. Haz clic derecho en el acceso directo a PowerShell y, luego, inícialo como administrador.
  3. Crea un entorno de Python aislado.
    python -m venv env
    .\env\Scripts\activate
  4. Navegue al directorio del proyecto y luego instale las dependencias. Si no estás en el directorio que contiene el código de muestra, navega al directorio que contiene el código de muestra hello_world. Luego, instala las dependencias:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. Ejecute la aplicación:
    python main.py
  6. En el navegador web, ingresa la siguiente dirección:
    http://localhost:8080

Configura tu servicio web para App Engine

Para implementar tu servicio web en App Engine, necesitas un archivo app.yaml. Este archivo de configuración define la configuración de tu servicio web para App Engine.

Para configurar tu servicio web para la implementación en App Engine, crea tu archivo app.yaml en el directorio raíz de tu proyecto, por ejemplo 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

Ten en cuenta que, para este servicio web simple, el archivo app.yaml debe definir solo la configuración del entorno de ejecución y los controladores para archivos estáticos.

Para servicios web más complicados, puedes configurar ajustes adicionales en tu archivo app.yaml, como escalamiento, controladores adicionales y otros elementos de aplicaciones, por ejemplo, variables del entorno y nombres de servicio. Para obtener más información y una lista de todos los elementos compatibles, consulta la referencia de app.yaml.

Próximos pasos

Ahora que has configurado, creado y probado tu servicio web, puedes implementar esta versión del servicio web en App Engine.