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 visualizza i dati segnaposto. L'obiettivo è assicurarti 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 Python 3 completando i seguenti passaggi:

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

    • Utilizza le tue credenziali utente Google Cloud per l'autenticazione con Google Cloud CLI e abilita 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

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 modello HTML con i dati del 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 tuo File requirements.txt:

    Flask==3.0.0
    

Prova il tuo 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 sei nella directory che contiene il codice di esempio, vai alla directory che contiene il codice di esempio hello_world. Quindi installa dependencies:
    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 le funzionalità di PowerShell per eseguire i pacchetti Python.

  1. Individua l'installazione di PowerShell.
  2. Fai clic con il tasto destro del mouse sulla scorciatoia di PowerShell e avviala 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 sei nella directory che contiene il codice campione, passa alla directory che contiene 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

Configurare il servizio web per App Engine

Per eseguire il deployment del servizio web in App Engine, devi disporre di 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 principale 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 l'impostazione di runtime e i gestori per i file statici.

Per servizi web più complicati, puoi configurare impostazioni aggiuntive nel tuo app.yaml, come scalabilità, gestori aggiuntivi e degli elementi dell'applicazione, come le variabili di ambiente e i nomi dei servizi. Per ulteriori informazioni e per un elenco di tutti gli elementi supportati, consulta la Riferimento app.yaml.

Passaggi successivi

Dopo aver configurato, creato e testato il servizio web, puoi di questa versione del tuo servizio web in App Engine.