Scrittura di un servizio web di base per App Engine

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

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

Prima di iniziare

  1. Se non hai ancora creato un progetto Google Cloud, creane uno.

  2. Se non lo hai già fatto, configura il tuo ambiente locale per lo sviluppo in Python 3 completando questi passaggi:

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

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

      gcloud auth application-default login
      

Strutturare i file dei servizi 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 in corso...

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

Per configurare il servizio web:

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

    Flask==3.0.0
    

Test del servizio web

Testa il tuo 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 che contiene il codice campione, vai alla directory che contiene il codice campione hello_world. 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 tuoi 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 che contiene il codice campione, vai a quella che contiene il codice campione hello_world. 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 tuo servizio web in App Engine, ti serve 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 root 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: 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

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

Per 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 di servizi. Per ulteriori informazioni e per un elenco di tutti gli elementi supportati, consulta il riferimento di app.yaml.

Passaggi successivi

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