Escribir un servicio web básico para App Engine

Escribe y prueba localmente un servicio web que sirva un archivo HTML estático con Flask. A continuación, crea los archivos de configuración que necesites para desplegar el servicio web en App Engine.

En este paso, creará y probará localmente una versión de un servicio web que muestra datos de marcador de posición. El objetivo es asegurarse de que el servicio web básico funciona antes de añadir Datastore y la autenticación de Firebase.

Antes de empezar

  1. Si aún no has creado un Google Cloud proyecto, crea un Google Cloud proyecto.

  2. Si aún no lo has hecho, configura tu entorno local para el desarrollo de Python 3 siguiendo estos pasos:

    • Descarga e instala Python 3 para desarrollar tu servicio web y ejecutar la CLI de Google Cloud.

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

      gcloud auth application-default login
      

Estructurar los archivos de un servicio web

El directorio del proyecto en el que 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 muestra un ejemplo de cómo configurar los archivos en el directorio de tu proyecto.

Escribir un servicio web

La primera iteración de tu servicio web usa Flask para servir 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. Añade comportamientos y estilos con 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 el archivo main.py, usa Flask para renderizar tu plantilla HTML con los datos de 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 necesites para tu servicio web en el archivo requirements.txt:

    Flask==3.0.0
    

Probar un servicio web

Prueba tu servicio web ejecutándolo de forma local en un entorno virtual:

Mac OS / Linux

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

Windows

Usa PowerShell para ejecutar tus paquetes de Python.

  1. Busca tu instalación de PowerShell.
  2. Haz clic con el botón derecho en el acceso directo a PowerShell y ejecútalo como administrador.
  3. Crea un entorno de Python aislado.
    python -m venv env
    .\env\Scripts\activate
  4. Ve al directorio de tu proyecto e instala las dependencias. Si no estás en el directorio que contiene el código de ejemplo, ve al directorio que contiene el hello_world código de ejemplo. A continuación, instala las dependencias:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. Ejecuta la aplicación:
    python main.py
  6. Introduce la siguiente dirección en el navegador web:
    http://localhost:8080

Configurar el servicio web para App Engine

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

Para configurar tu servicio web para el despliegue en App Engine, crea el 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: 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

Ten en cuenta que, en este sencillo servicio web, tu archivo app.yaml solo necesita definir el ajuste del tiempo de ejecución y los controladores de los archivos estáticos.

En el caso de los servicios web más complejos, puedes configurar ajustes adicionales en tu app.yaml, como el escalado, los controladores adicionales y otros elementos de la aplicación, como las variables de entorno y los nombres de servicio. Para obtener más información y ver una lista de todos los elementos admitidos, consulta la referencia de app.yaml.

Pasos siguientes

Ahora que ha configurado, creado y probado su servicio web, puede implementar esta versión en App Engine.