[Python] Run Flask on Google App Engine

A personal note outlining the steps to get Flask, the Python web framework, to work on Google App Engine. In carrying out the following procedure, we refer to the following articles for many parts.

-[Run Flask on Google App Engine] (http://blog.kaneshin.co/entry/2016/09/05/010804)

-[Until using Flask on Google App Engine] (http://mw17.hatenablog.jp/entry/2015/09/18/004714)

1. Install Python version 2.7 (anaconda2-4.2.0)

Google App Engine (SE) requires Python version 2.7. When I built the Django environment first, I set it up so that I could use the specified version of the anaconda virtual environment, so I'll use that as well. (* For details, refer to steps 3 to 7 in the following article.) -[[Python] Django environment construction (pyenv + pyenv-virtualenv + Anaconda) for macOS] (http://qiita.com/togoturns/items/b2ae361a669933c823f5)

Below, continue.

Terminal


$ pyenv global anaconda2-4.2.0 (#The specified version of the virtual environment is set for all directories)
$ pyenv virtualenv anaconda2-4.2.0 flask001
 (# "flask001"With the name, version"anaconda2-4.2.0"Create a new virtual environment for)
$ python --version (#python version check)
    Python 2.7.12 :: Anaconda 4.2.0 (x86_64)  
$ pyenv versions
    system
  * anaconda2-4.2.0
    anaconda3-4.2.0
    flask001
 (#In the virtual environment that can be specified with pyenv,"flask001"Is added)

2. After creating the directory to install Flask, set the virtual environment created in step 1 in the directory.

Terminal


$ mkdir myflask (#Directory to install Flask"myflask"Create)
$ cd myflask (# "myflask"Move to directory)
$ pyenv local flask001 (# "myflask"Virtual environment in the directory"flask001"The set)
$ pyenv versions
    system
    anaconda2-4.2.0
    anaconda3-4.2.0
  * flask001
 (#It is possible to automatically enter the virtual environment created by virtualenv just by moving to the specified directory.)

3. Download Google Cloud SDK package file

Download the SDK archive package for Mac OS X (x86_64) from the following page, and place all the extracted files after decompression under any directory. -[Quick Start for Mac OS X (Install Cloud SDK)] (https://cloud.google.com/sdk/docs/quickstart-mac-os-x)

Terminal


$ cd $HOME
$ mkdir .py_appengine
$ cd .py_appengine

(# ".py_appengine"Create a directory and place the Cloud SDK file downloaded and expanded under the directory.)

4. Add the SDK directory path to your .bash_profile

Terminal


$ cd $HOME
$ vim ~/.bash_profile (# .bash_Describe the following contents in the profile file)

  # Set path for Python_GoogleAppEngine
  export PATH="$PATH:$HOME/.py_appengine:$HOME/.py_appengine/google-cloud-sdk/platform/google_appengine"

Terminal


source ~/.bash_profile (#Reflect the settings)

5. Install Google Cloud SDK

Terminal


$ cd $HOME/.py_appengine
$ ./google-cloud-sdk/install.sh (# install.Run sh to initialize the SDK)

  # "You must log in to continue. Would you like to log in (Y/n)?"
  # "Y"Enter to launch the browser and open the Google Cloud Platform page.
  #When you log in, Google Cloud SDK authentication is complete.

$ ./google-cloud-sdk/bin/gcloud init (#Run gcloud init to initialize the SDK)

6. Install Flask

Terminal


$ cd $HOME/myflask
$ mkdir lib (#Create a lib directory to install Flask)
$ pip install -t lib flask (#Install Flask in the lib directory)

7. Place 3 files in the same hierarchy as the lib directory

Download the 3 files on github and put them in the same hierarchy as the lib directory. (* Placed under the "myflask" directory here. Also, all 3 files are used with the default settings)

python


myflask
 |_ lib/
 |_ app.yaml - (1)
 |_ appengine_config.py - (2)
 |_ main.py - (3)

(1) app.yaml file Describes the request handler to App Engine and the path application settings to static files.

Terminal


$ cd $HOME/myflask

[app.yaml]


# This file specifies your Python application's runtime configuration
# including URL routing, versions, static file uploads, etc. See
# https://developers.google.com/appengine/docs/python/config/appconfig
# for details.

runtime: python27
api_version: 1
threadsafe: yes

# Handlers define how to route requests to your application.
handlers:

# App Engine serves and caches static files contained in the listed directories
# (and subdirectories). Uncomment and set the directory as needed.
#- url: /client
#  static_dir: client

# This handler tells app engine how to route requests to a WSGI application.
# The script value is in the format <path.to.module>.<wsgi_application>
# where <wsgi_application> is a WSGI application object.
- url: .*  # This regex directs all routes to main.app
  script: main.app

# Third party libraries that are included in the App Engine SDK must be listed
# here if you want to use them.  See
# https://developers.google.com/appengine/docs/python/tools/libraries27 for
# a list of libraries included in the SDK.  Third party libs that are *not* part
# of the App Engine SDK don't need to be listed here, instead add them to your
# project directory, either as a git submodule or as a plain subdirectory.
# TODO: List any other App Engine SDK libs you may need here.
#libraries:
#- name: jinja2
#  version: latest

(2) appengine_config.py file Describes the settings for loading the lib directory when running App Engine.

[appengine_config.py]


# `appengine_config.py` is automatically loaded when Google App Engine
# starts a new instance of your application. This runs before any
# WSGI applications specified in app.yaml are loaded.
from google.appengine.ext import vendor

# Third-party libraries are stored in "lib", vendoring will make
# sure that they are importable by the application.
vendor.add('lib')

(3) main.py file Import Flask in a file and describe the settings for routing.

[main.py]


# `main` is the top level module for your Flask application.

# Import the Flask Framework
from flask import Flask
app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, Nothing at this URL.', 404

@app.errorhandler(500)
def application_error(e):
    """Return a custom 500 error."""
    return 'Sorry, unexpected error: {}'.format(e), 500

(reference) -[[Python] Getting Started with Decorators] (http://www.yoheim.net/blog.php?q=20160607)

8. Confirmation of operation in local environment

Terminal


$ dev_appserver.py . (#Dev in the App Engine SDK_appserver.Run py file)

  # "Do you want to continue (Y/n)?"Is displayed"y"Enter

After executing the command, enter "http: // localhost: 8080" in the address field of the browser. If "Hello World!" Is displayed, it is successful.

9. Create a project on the Google Cloud Platform administration screen

Sign in to the Google Cloud Platform page and create a project to deploy from the admin screen.

  1. Sign in to Google Cloud Platform Administration Screen (Dashboard)
  2. Click the hamburger menu (tools and services) at the top left of the screen
  3. Click "IAM and Management"
  4. Click "All Projects"
  5. Click "+ Create Project"
  6. Enter the project name in "New Project" and click "Create"
  7. Copy the assigned to the newly created project

10. Deploy to Google App Engine

Terminal


$ open https://appengine.google.com/start (#Sign in to the App Engine site and first create an App Engine resource to use in your project *"asia-northeast1"choose)

$ appcfg.py update -A <Project ID> -V v1 . (# <Project ID> には手順 9 で用意したProject ID を入力)

<reference>
#If this is not your first deployment, first execute the following command to set the project as the default, and then execute the above command again.
$ appcfg.py set_default_version -V v1 -A <Project ID>

After executing the command, enter "https: // .appspot.com" in the address field of the browser. If "Hello World!" Is displayed, it is successful.

(reference) -[Note on Go preferences in GCP AE] (http://qiita.com/mgoldchild/items/4934819f91cc628f3b1f)

Recommended Posts

[Python] Run Flask on Google App Engine
Tweet (API 1.1) on Google App Engine for Python
Deploy a Django application on Google App Engine (Python3)
PIL with Python on Windows 8 (for Google App Engine)
How to use Django on Google App Engine / Python
Use ndb.tasklet on Google App Engine
Run Cloud Dataflow (Python) from App Engine
Until you run a Flask application on Google App Engine for the time being
Use external modules on Google App Engine
Use Django's ImageField on App Engine / Python
Vienna with Python + Flask web app on Jenkins
Run Python web apps on NGINX + NGINX Unit + Flask
Build Python3 + flask environment on GCP Compute Engine
Run Flask on CentOS with python3.4, Gunicorn + Nginx.
Deploy a Python app on Google App Engine and integrate it with GitHub
Run Openpose on Python (Windows)
Run Tensorflow 2.x on Python 3.7
Google App Engine / Python development environment construction procedure (late 2014)
(Beginner) Basic usage of Datastore on Google App Engine
Run Python CGI on CORESERVER
Run unix command on python
Getting Started with Google App Engine for Python & PHP
Runtime version of Google App Engine / Python Standard Environment
Sample to put Python Flask web app on Azure App Service (Web App)
Deploy your Go app on Google App Engine with GitHub Actions
Run the app with Flask + Heroku
Google App Engine development with Docker
Run Python on Schedule on AWS Lambda
Run TensorFlow Docker Image on Python3
Java 1 1 support from Google App Engine
Deploy Flask app on heroku (bitterly)
Deploy the Flask app on Heroku
Deploy the Flask app on heroku
Run Keras on Google Colaboratory TPU
Periodically run Python on Heroku Scheduler
Do you have any recommendations for a commentary book on Google App Engine / Python development?
Publish the site for free on Google App Engine (personal memorandum)
Settings when writing Google App Engine / Python apps in Intellij Idea
Building a development environment with Maven on Google App Engine [Java]
Using properties files with Flexible Environment Java 8 on Google App Engine
Run servo with Python on ESP32 (Windows)
Run AzureKinect in Python on Christmas Eve.
[Google App Engine] User Objects (Japanese translation)
Run servomotor on Raspberry Pi 3 using python
Launch a Flask app in Python Anywhere
Easy web app with Python + Flask + Heroku
[Python] Run Headless Chrome on AWS Lambda
I can't deploy with google app engine
Run Python code on A2019 Community Edition
Run Python in C ++ on Visual Studio 2017
Run python wsgi server on NGINX Unit
Periodically run a python program on AWS Lambda
Install and run Python3.5 + NumPy + SciPy on Windows 10
Put MicroPython on Windows to run ESP32 on Python
Python on Windows
About the problem that the python version of Google App Engine does not mesh
Run Google Analytics API (core v3) in python
Run Python YOLOv3 in C ++ on Visual Studio 2017
Notes on Flask
How to run MeCab on Ubuntu 18.04 LTS Python
Run Zookeeper x python (kazoo) on Mac OS X