Skip to content

Instantly share code, notes, and snippets.

@pumpkinpietea
Last active February 25, 2018 03:47
# -*- 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"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment