2018/10/14

GCP: Google App EngineのランタイムPython3.7を使ってみる2 -- Rest API

前回メモ(hello world with Python3.7)の続編。Restサービスの立上げ。
App Engine APIs が使えなくなっているので、代わりにGCPのPython用のライブラリを使う。(例えば、Datastoreの読み書きにndbは使えない。)

  • Goal
    GAE(Google App Engine) + python3.7ランタイム上にREST API(メソッドはPOST)を作成する。
    APIが呼び出されたら、GCP(Google Cloud Platform)のDatastoreに新規Entity(レコード)を追加する。
  • case
    名前、点数、教科名をjsonでPOSTしたら、GCPのDatastoreに書き込みして、Keyを返信する。
  • How
    1. 開発前準備
    1)開発環境に、google-cloud-datastoreをインストール
    2)
    GOOGLE_APPLICATION_CREDENTIALS 環境変数を設定
    あくまで、ローカルでテストするために必要。
    以下コマンドを打つと、betaコンポーネントのダウンロードを聞かれる。
    「Y」を入力すると、ダウンロードされて環境変数の設定までしてくれる。
    $ gcloud beta auth application-default login

    2. requirements.txt の中身。google-cloud-datastoreも追加すること。

    # This requirements file lists all third-party dependencies for this project.
    #
    # Run 'pip install -r requirements.txt -t lib/' to install these dependencies
    # in `lib/` subdirectory.
    Flask==1.0.2
    google-cloud-datastore==1.7.0


    3. main.py の中身。

    # -*- coding: utf-8 -*-
    # Import the Flask Framework
    from flask import Flask, request, jsonify, abort
    from google.cloud import datastore
    import datetime
    app = Flask(__name__)
    # rootにアクセスされた場合のコントロール
    @app.route('/')
    def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello!' # abort(402) -- abortにしてもよい
    # 今回は、/addtest を Postで呼び出すという想定
    @app.route('/addtest', methods=['POST'])
    def runaddtest():
    # jsonがなかったり、Nameがなければ、400で返す
    if not request.json or not 'name' in request.json:
    abort(400)
    # 認証
    datastore_client = datastore.Client(project='<project name>')
    # Kind名を設定--- テーブル名みたいなもの
    kind = '<kind name>'
    # KEYを作成−−− このケースは、自分で設定せずに、GCPがKEYを作成
    item_key = datastore_client.key(kind)
    # それぞれの要素をjsonからパース
    item = datastore.Entity(key=item_key)
    item['name'] = request.json['name']
    item['points'] = request.json['points']
    item['subject'] = request.json['subject']
    item['creationdate'] = datetime.datetime.now()
    # datastoreに登録する
    datastore_client.put(item)
    # 返信用のjson作成。登録したEntityのKeyを返す
    replymes = {
    'id': item.key.id
    }
    # json と STATUS 201を返す
    return jsonify({'result': replymes}), 201
    @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
    # For local testing
    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.
    app.run(host='127.0.0.1', port=8080, debug=True)

  • Result --- curlのサンプルと結果
    Toshiのhistoryが67点


    $ curl -i -H "Content-Type: application/json" -X POST -d '{"name":"toshi","points":67,"subject":"history"}' https://.appspot.com/addtest
    HTTP/2 201 
    content-type: application/json
    x-cloud-trace-context: 4140694e3538666bb96627febc6130e4;o=1
    date: Sun, 14 Oct 2018 14:08:21 GMT
    server: Google Frontend
    content-length: 35
    alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
    {"result":{"id":5635703144710144}}



0 件のコメント:

コメントを投稿