Flaskメモ

トップ > アラカルト > Flaskメモ

環境

Flask をインストールする

# yum -y install python python-setuptools python-devel mysql mysql-devel gcc
# easy_install pip
# easy_install Flask
# pip install MySQL-python

Hello world!

# vi hello.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
  return "Hello World!\n"

if __name__ == '__main__':
  app.run()

# python hello.py
別のコンソールから
# curl http://127.0.0.1:5000/

簡単な REST サーバ

# mysql -h localhost -p
mysql> create database mydb;
mysql> use mydb;
mysql> create table users ( id int AUTO_INCREMENT, user_id varchar(32) unique, user_name varchar(256) unique, index(id) );
mysql> quit

# vi users.py
import MySQLdb
import json
from flask import Flask, request, jsonify
app = Flask(__name__)

passwd = "パスワード"

def selectDb(sql, param):
  connection = MySQLdb.connect(db="mydb", user="root", passwd=passwd)
  cursor = connection.cursor()
  cursor.execute(sql, param)
  result = cursor.fetchall()
  cursor.close()
  connection.close()
  return result

def execDb(sql, param):
  connection = MySQLdb.connect(db="mydb", user="root", passwd=passwd)
  cursor = connection.cursor()
  cursor.execute(sql, param)
  connection.commit()
  cursor.close()
  connection.close()

@app.route('/users', methods=['POST'])
def createUser():
  execDb("insert into users ( user_id, user_name ) values ( %(user_id)s, %(user_name)s )", request.json)
  return ""

@app.route('/users', methods=['GET'])
def listUsers():
  data = selectDb("select user_id, user_name from users", {});
  ret = { "users" : [] }
  for row in data:
    ret['users'].append({ "user_id" : row[0], "user_name" : row[1] })
  return json.dumps(ret)

@app.route('/users/<string:user_id>', methods=['GET'])
def getUser(user_id):
  data = selectDb("select user_id, user_name from users where user_id = %(user_id)s", { "user_id" : user_id });
  ret = { "user" : { "user_id" : data[0][0], "user_name" : data[0][1] } }
  return json.dumps(ret)

@app.route('/users/<string:user_id>', methods=['POST'])
def updateUser(user_id):
  execDb("update users set user_name = %(user_name)s where user_id = %(user_id)s",
     { "user_id" : user_id, "user_name" : request.json['user_name'] })
  return ""

@app.route('/users/<string:user_id>', methods=['DELETE'])
def deleteUser(user_id):
  execDb("delete from users where user_id = %(user_id)s", { "user_id" : user_id })
  return ""

if __name__ == '__main__':
  app.run()

# python users.py

別のコンソールから

ユーザの追加
# curl -s -X POST -H 'Content-Type: application/json' -d '{ "user_id": "U12345", "user_name" : "tanaka" }'  http://127.0.0.1:5000/users

ユーザの一覧
# curl -s -X GET http://127.0.0.1:5000/users | python -mjson.tool

ユーザの詳細
# curl -s -X GET http://127.0.0.1:5000/users/U12345 | python -mjson.tool

ユーザの変更
# curl -s -X POST -H 'Content-Type: application/json' -d '{ "user_name" : "suzuki" }'  http://127.0.0.1:5000/users/U12345

ユーザの削除
# curl -s -X DELETE http://127.0.0.1:5000/users/U12345

Copyright (C) 2016 杜甫々
初版:2016年6月4日 最終更新:2016年6月21日
http://www.tohoho-web.com/ex/flask.html