2018/02/25

GCP: GAE上にAPI(POST)を作成ーDatastoreの操作(Create) ー Python



  • Goal
    GAE(Google App Engine)上にREST API(メソッドはPOST)を作成する。
    APIが呼び出されたら、GCP(Google Cloud Platform)のDatastoreに新規Entity(レコード)を追加する。言語・環境はPython+flask。
  • case
    名前、点数、教科名をjsonでPOSTしたら、GCPのDatastoreに書き込みして、Keyを返信する。
  • How
    1:開発環境は、以下でセットアップ
      Ubuntu16.4 + Pyenv:Python2.7.13 on GCE
      GCP: Google App Engine上にPython(Flask)アプリを立ち上げる手順

    2:ライブラリのセットアップ
      app.yaml に、flaskの記述を追加
      - name: flask
        version: 0.12

    3:mainプログラム と curl 結果

    # -*- coding: utf-8 -*-
    # app.yamlに追記すればOK.libで持っていかなくてもよい。
    from flask import Flask,request,jsonify,abort
    # GCPのDatastoreを使うには必要。libで持っていかなくても、GAE上にある
    from google.appengine.ext import ndb
    import datetime
    app = Flask(__name__)
    # DatastoreのEntityの定義
    class test(ndb.Model):
    name = ndb.StringProperty()
    points = ndb.IntegerProperty()
    subject = ndb.StringProperty()
    creationdate = ndb.DateTimeProperty()
    # rootにアクセスされた場合のコントール
    @app.route('/')
    def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello!'#abort(402) -- abortにしてもよい
    # 今回は、/addtest を Postで呼び出すという想定
    @app.route('/addtest', methods=['POST'])
    def runaddtest():
    testrecord = {}
    # jsonがなかったり、Nameがなければ、400で返す
    if not request.json or not 'name' in request.json:
    abort(400)
    # 登録するために、jsonを各項目にパースする
    testrecord = test(
    name = request.json['name'],
    points = request.json['points'],
    subject = request.json['subject'],
    creationdate = datetime.datetime.now()
    )
    # datastoreに登録する
    testrecord.put()
    # 登録したEntityのKeyの値を取ってくる。
    recordid = str(testrecord.key.id())
    # 返信用のjson作成。登録したEntityのKeyを返す
    replymes = {
    'id': recordid
    }
    # 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
    $ curl -i -H "Content-Type: application/json" -X POST -d '{"name":"toshi","points":81,"subject":"kokugo"}' https://<project>.appspot.com/addtest
    HTTP/2 201
    content-type: application/json
    x-cloud-trace-context: XXXXXX;o=1
    date: Sun, 25 Feb 2018 03:15:06 GMT
    server: Google Frontend
    content-length: 51
    alt-svc: hq=":443"; ma=000; quic=531; quic=339; quic=338; quic=337; quic=335,quic=":443"; ma=2592000; v="41,39,38,37,35"
    {
    "result": {
    "id": "56765079040"
    }
    }
    view raw test-curl hosted with ❤ by GitHub

    4:Datastoreの結果

  • Thanks!

0 件のコメント:

コメントを投稿