Writing a Basic Web Service for App Engine

Write and locally test a web service that serves a static HTML file using Flask. Then, create the configuration files that you need for deploying the web service to App Engine.

In this step, you create and locally test a version of a web service that displays placeholder data. The goal here is to ensure that your basic web service is working before adding Cloud Datastore and Firebase authentication.

Before you begin

  1. If you have not already created a GCP project, create a GCP project.

  2. If you have not already, set up your local environment for Python 3 development by completing the following:

    • Download and install Python 2 and 3 for developing your web service and running the Cloud SDK.

    • Install virtualenv for local testing by running the following command:

      Mac OS / Linux

      sudo pip install virtualenv

      Windows

      pip install virtualenv

    • Use your GCP user credentials to authenticate with the Cloud SDK and enable local testing with Cloud Datastore:

      gcloud auth application-default login
      

      Tip: For more extensive testing, it is recommended that you set up a service account rather than using user-end credentials. For more information on service accounts and other types of authentication, see Authentication Overview.

Structuring your web service files

The project directory where you create your web service will have the following file structure:

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

Tip: You can download copies of these files before following along.

Writing your web service

The initial iteration of your web service uses Flask to serve a Jinja-based HTML template.

To set up your web service:

  1. Create your templates/index.html file:

    <!doctype html>
    <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. Add behaviors and styles with static/script.js and static/style.css files:

    'use strict';
    
    window.addEventListener('load', function () {
    
      console.log("Hello World!");
    
    });
    body {
      font-family: "helvetica", sans-serif;
      text-align: center;
    }
    
  3. In your main.py file, use Flask to render your HTML template with the placeholder data:

    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 all dependencies you will need for your web service in your requirements.txt file:

    Flask==1.0.2
    

Testing your web service

Test your web service by running it locally, using virtualenv to handle dependencies:

Mac OS / Linux

  1. Create an isolated Python environment in a directory external to your project and activate it:
    virtualenv env
    source env/bin/activate
  2. Navigate to your project directory and install dependencies:
    cd YOUR_PROJECT
    pip install  -r requirements.txt
  3. Run the application:
    python main.py
  4. In your web browser, enter the following address:
    http://localhost:8080

Windows

Use PowerShell to run your Python packages.

  1. Locate your installation of PowerShell.
  2. Right-click on the shortcut to PowerShell and start it as an administrator.
  3. Create an isolated Python environment in a directory external to your project and activate it:
    virtualenv env
    env\Scripts\activate
  4. Navigate to your project directory and install dependencies:
    cd YOUR_PROJECT
    pip install -r requirements.txt
  5. Run the application:
    python main.py
  6. In your web browser, enter the following address:
    http://localhost:8080

Configuring your web service for App Engine

To deploy your web service to App Engine, you need an app.yaml file. This configuration file defines your web service's settings for App Engine.

To configure your web service for deployment to App Engine, create your app.yaml file in the root directory of your project, for example building-an-app:

runtime: python37

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

Notice that for this simple web service, your app.yaml file needs to define only the runtime setting and handlers for static files.

For more complicated web services, you can configure additional settings in your app.yaml, like scaling, additional handlers, and other application elements like environment variables and service names. For more information and a list of all the supported elements, see the app.yaml reference.

Next steps

Now that you've configured, created, and tested your web service, you can deploy this version of your web service to App Engine.

このページは役立ちましたか?評価をお願いいたします。

フィードバックを送信...

App Engine standard environment for Python 3