כתיבה של שירות אינטרנט בסיסי ל-App Engine

לכתוב ולבדוק באופן מקומי שירות אינטרנט שמציג קובץ HTML סטטי באמצעות Flask. לאחר מכן, יוצרים את קובצי ההגדרות שצריך כדי לפרוס את שירות האינטרנט ב-App Engine.

בשלב הזה, יוצרים גרסה של שירות אינטרנט ומבצעים בה בדיקה מקומית. הגרסה הזו מציגה נתוני placeholder. המטרה כאן היא לוודא ששירות האינטרנט הבסיסי שלכם פועל לפני שמוסיפים את Datastore ואת אימות Firebase.

לפני שמתחילים

  1. אם עדיין לא יצרתם Google Cloud פרויקט, יוצרים Google Cloud פרויקט.

  2. אם עדיין לא עשיתם זאת, אתם צריכים להגדיר את הסביבה המקומית לפיתוח ב-Python 3. כדי לעשות זאת:

    • מורידים ומתקינים את Python 3 כדי לפתח את שירות האינטרנט ולהריץ את Google Cloud CLI.

    • משתמשים בפרטי הכניסה של המשתמש Google Cloud כדי לבצע אימות באמצעות Google Cloud CLI ולהפעיל בדיקות מקומיות באמצעות Datastore:

      gcloud auth application-default login
      

הגדרת המבנה של קובצי שירות האינטרנט

תיקיית הפרויקט שבה יוצרים את שירות האינטרנט תכלול את מבנה הקבצים הבא:

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

בקטעים הבאים מופיעה דוגמה להגדרת הקבצים בספריית הפרויקט.

כתיבת שירות האינטרנט

האיטרציה הראשונית של שירות האינטרנט משתמשת ב-Flask כדי להציג תבנית HTML שמבוססת על Jinja.

כדי להגדיר את שירות האינטרנט:

  1. יוצרים את הקובץ 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. הוספת התנהגויות וסגנונות באמצעות קובצי static/script.js ו-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. בקובץ main.py, משתמשים ב-Flask כדי לעבד את תבנית ה-HTML עם נתוני ה-placeholder:

    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. מגדירים את כל יחסי התלות שדרושים לשירות האינטרנט בקובץ requirements.txt:

    Flask==3.0.0
    

בדיקת שירות האינטרנט

בודקים את שירות האינטרנט על ידי הפעלתו באופן מקומי בסביבה וירטואלית:

Mac OS / Linux

  1. יוצרים סביבת Python מבודדת:
    python3 -m venv env
    source env/bin/activate
  2. אם אתם לא בספרייה שמכילה את הקוד לדוגמה, עוברים לספרייה שמכילה את הקוד לדוגמה hello_world. לאחר מכן מתקינים את יחסי התלות:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. מריצים את האפליקציה:
    python main.py
  4. בדפדפן האינטרנט, מזינים את הכתובת הבאה:
    http://localhost:8080

Windows

משתמשים ב-PowerShell כדי להריץ את חבילות Python.

  1. מוצאים את ההתקנה של PowerShell.
  2. לוחצים לחיצה ימנית על קיצור הדרך ל-PowerShell ומפעילים אותו כאדמין.
  3. יוצרים סביבת Python מבודדת.
    python -m venv env
    .\env\Scripts\activate
  4. עוברים לספריית הפרויקט ומתקינים את יחסי התלות. אם אתם לא בספרייה שמכילה את הקוד לדוגמה, עוברים לספרייה שמכילה את הקוד לדוגמה hello_world. לאחר מכן, מתקינים יחסי תלות:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. מריצים את האפליקציה:
    python main.py
  6. בדפדפן האינטרנט, מזינים את הכתובת הבאה:
    http://localhost:8080

הגדרת שירות האינטרנט ל-App Engine

כדי לפרוס את שירות האינטרנט ב-App Engine, צריך קובץ app.yaml. קובץ התצורה הזה מגדיר את ההגדרות של שירות האינטרנט שלכם ב-App Engine.

כדי להגדיר את שירות האינטרנט לפריסה ב-App Engine, יוצרים את הקובץ app.yaml בספריית השורש של הפרויקט, לדוגמה 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

שימו לב: בשביל שירות האינטרנט הפשוט הזה, בקובץ app.yaml צריך להגדיר רק את הגדרות זמן הריצה ואת ה-handlers של קבצים סטטיים.

בשירותי אינטרנט מורכבים יותר, אפשר להגדיר הגדרות נוספות ב-app.yaml, כמו שינוי קנה מידה, רכיבי handler נוספים ורכיבי אפליקציה אחרים כמו משתני סביבה ושמות שירותים. מידע נוסף ורשימה של כל האלמנטים הנתמכים זמינים במאמר בנושא app.yaml.

השלבים הבאים

אחרי שמגדירים, יוצרים ובודקים את שירות האינטרנט, אפשר לפרוס את הגרסה הזו של שירות האינטרנט ב-App Engine.