Escribir un servicio web básico para App Engine

Escriba y pruebe localmente un servicio web que proporcione un archivo HTML estático utilizando Flask. Luego, cree los archivos de configuración que necesita para implementar 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 aquí es garantizar que su servicio web básico esté funcionando antes de agregar la autenticación de Datastore y Firebase.

Antes de comenzar

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

  2. Si aún no lo ha hecho, configure su entorno local para el desarrollo de Python 3 completando lo siguiente:

    • Descargue e instale Python 3 para desarrollar su servicio web y ejecutar la CLI de Google Cloud.

    • Usa tu Google Cloud Credenciales de usuario para autenticarse con Google Cloud CLI y habilitar pruebas locales con Datastore:

      gcloud auth application-default login
      

Estructurar los archivos de sus servicios web

El directorio del proyecto donde crea su 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

Las siguientes secciones proporcionan un ejemplo de cómo configurar los archivos en el directorio de su proyecto.

Escribe tu servicio web

La iteración inicial de su servicio web utiliza Flask para ofrecer una plantilla HTML basada en Jinja .

Para configurar su servicio web:

  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. Agregue 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 su archivo main.py , use Flask para representar su 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. Configure todas las dependencias que necesitará para su servicio web en su archivo requirements.txt :

    Flask==3.0.0
    

Pruebe su servicio web

Pruebe su servicio web ejecutándolo localmente en un entorno virtual:

MacOS/Linux

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

ventanas

Utilice PowerShell para ejecutar sus paquetes de Python.

  1. Ubique su instalación de PowerShell .
  2. Haga clic derecho en el acceso directo a PowerShell e inícielo como administrador.
  3. Cree un entorno Python aislado .
    python -m venv env
    .\env\Scripts\activate
  4. Navegue al directorio de su proyecto e instale las dependencias. Si no está en el directorio que contiene el código de muestra, navegue hasta el directorio que contiene el código de muestra hello_world . Luego, instale las dependencias:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. Ejecute la aplicación:
    python main.py
  6. En su navegador web, ingrese la siguiente dirección:
    http://localhost:8080

Configura tu servicio web para App Engine

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

Para configurar su servicio web para su implementación en App Engine, cree su archivo app.yaml en el directorio raíz de su 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

Tenga en cuenta que para este servicio web simple, su archivo app.yaml necesita definir solo la configuración del tiempo de ejecución y los controladores para archivos estáticos.

Para servicios web más complicados, puede configurar ajustes adicionales en su app.yaml , como escalado, controladores adicionales y otros elementos de la aplicación, como variables de entorno y nombres de servicios. Para obtener más información y una lista de todos los elementos admitidos, consulte la referencia app.yaml .

Próximos pasos

Ahora que configuró, creó y probó su servicio web, puede implementar esta versión de su servicio web en App Engine.