Scrivere un servizio web di base per App Engine

Scrivi e testa localmente un servizio web che pubblica un file HTML statico utilizzando Flask. Quindi, crea i file di configurazione necessari per eseguire il deployment del servizio web in App Engine.

In questo passaggio, crei e testi localmente una versione di un servizio web che mostra dati segnaposto. L'obiettivo è assicurarsi che il servizio web di base funzioni prima di aggiungere l'autenticazione Datastore e Firebase.

Prima di iniziare

  1. Se non l'hai già fatto, crea un Google Cloud progetto, crea un Google Cloud progetto.

  2. Se non l'hai già fatto, configura l'ambiente locale per lo sviluppo Python 3 completando i seguenti passaggi:

    • Scarica e installa Python 3 per sviluppare il servizio web ed eseguire Google Cloud CLI.

    • Utilizza le tue Google Cloud credenziali utente per eseguire l'autenticazione con la Google Cloud CLI e abilitare i test locali con Datastore:

      gcloud auth application-default login
      

Struttura i file del servizio web

La directory del progetto in cui crei il servizio web avrà la seguente struttura di file:

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

Le sezioni seguenti forniscono un esempio di come configurare i file nella directory del progetto.

Scrittura del servizio web

L'iterazione iniziale del servizio web utilizza Flask per pubblicare un modello HTML basato su Jinja.

Per configurare il servizio web:

  1. Crea il file 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. Aggiungi comportamenti e stili con i file 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. Nel file main.py, utilizza Flask per eseguire il rendering del modello HTML con i dati segnaposto:

    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 tutte le dipendenze necessarie per il servizio web nel file requirements.txt:

    Flask==3.1.3; python_version >= '3.9'
    

Test del servizio web

Testa il servizio web eseguendolo localmente in un ambiente virtuale:

Mac OS / Linux

  1. Crea un ambiente Python isolato:
    python3 -m venv env
    source env/bin/activate
  2. Se non ti trovi nella directory contenente il codice campione, vai alla directory contenente il hello_world codice campione. Quindi, installa le dipendenze:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. Esegui l'applicazione:
    python main.py
  4. Nel browser web, inserisci il seguente indirizzo:
    http://localhost:8080

Windows

Utilizza PowerShell per eseguire i pacchetti Python.

  1. Individua l'installazione di PowerShell.
  2. Fai clic con il tasto destro del mouse sul collegamento a PowerShell e avvialo come amministratore.
  3. Crea un ambiente Python isolato.
    python -m venv env
    .\env\Scripts\activate
  4. Naviga alla directory del progetto e installa le dipendenze. Se non ti trovi nella directory contenente il codice campione, vai alla directory contenente il hello_world codice campione. Quindi, installa le dipendenze:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. Esegui l'applicazione:
    python main.py
  6. Nel browser web, inserisci il seguente indirizzo:
    http://localhost:8080

Configurazione del servizio web per App Engine

Per eseguire il deployment del servizio web in App Engine, è necessario un file app.yaml. Questo file di configurazione definisce le impostazioni del servizio web per App Engine.

Per configurare il servizio web per il deployment in App Engine, crea il file app.yaml nella directory radice del progetto, ad esempio 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: python314

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

Tieni presente che, per questo semplice servizio web, il file app.yaml deve definire solo l'impostazione di runtime e i gestori per i file statici.

Per i servizi web più complessi, puoi configurare impostazioni aggiuntive in app.yaml, come scalabilità, gestori aggiuntivi e altri elementi dell'applicazione come variabili di ambiente e nomi dei servizi. Per ulteriori informazioni e un elenco di tutti gli elementi supportati, consulta il app.yaml riferimento.

Passaggi successivi

Ora che hai configurato, creato e testato il servizio web, puoi eseguire il deployment di questa versione del servizio web in App Engine.