説明
これは、ネイティブウェブアプリケーションとして IRIS にデプロイできる Flask アプリケーションのテンプレートです。
インストール
- リポジトリをクローンする
- 仮想環境を作成する
- 要件をインストールする
- docker-compose ファイルを実行する
git clone
cd iris-flask-template
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
docker-compose up
使用法
ベース URL は http://localhost:53795/flask/
です。
エンドポイント
/iris
- IRISAPP ネームスペースに存在する上位 10 個のクラスを持つ JSON オブジェクトを返します。/interop
- IRIS の相互運用性フレームワークをテストするための ping エンドポイント。/posts
- Post オブジェクトの単純な CRUD エンドポイント。/comments
- Comment オブジェクトの単純な CRUD エンドポイント。
このテンプレートからの開発方法
WSGI 導入記事をご覧ください: wsgi-introduction。
概要: セキュリティポータルで DEBUG
フラグをトグルすると、開発作業の過程で変更内容がアプリケーションに反映されるようになります。
コードの説明
app.py
これはアプリケーションのメインのファイルです。 Flask アプリケーションとエンドポイントが含まれます。
from flask import Flask, jsonify, request
from models import Comment, Post, init_db
from grongier.pex import Director
import iris
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'iris+emb://IRISAPP'
db = init_db(app)
from flask import Flask, jsonify, request
: Flask ライブラリをインポートします。from models import Comment, Post, init_db
: モデルとデータベース初期化関数をインポートします。from grongier.pex import Director
: Flask アプリを IRIS 相互運用性フレームワークにバインドする Director クラスをインポートします。import iris
: IRIS ライブラリをインポートします。app = Flask(__name__)
: Flask アプリケーションを作成します。app.config['SQLALCHEMY_DATABASE_URI'] = 'iris+emb://IRISAPP'
: データベース URI を IRISAPP ネームスペースに設定します。iris+emb
URI スキームは、埋め込み接続として IRIS に接続するために使用されます(別の IRIS インスタンスの必要はありません)。
db = init_db(app)
: Flask アプリケーションでデータベースを初期化します。
models.py
このファイルには、アプリケーションの SQLAlchemy モデルが含まれます。
from dataclasses import dataclass
from typing import List
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
@dataclass
class Comment(db.Model):
id:int = db.Column(db.Integer, primary_key=True)
content:str = db.Column(db.Text)
post_id:int = db.Column(db.Integer, db.ForeignKey('post.id'))
@dataclass
class Post(db.Model):
__allow_unmapped__ = True
id:int = db.Column(db.Integer, primary_key=True)
title:str = db.Column(db.String(100))
content:str = db.Column(db.Text)
comments:List[Comment] = db.relationship('Comment', backref='post')
説明することは特にありません。モデルはデータクラスとして定義されており、db.Model
クラスのサブクラスです。
__allow_unmapped__
属性は、comments
属性を使用せずに Post
オブジェクトを作成できるようにするために使用する必要があります。
dataclasses
はオブジェクトを JSON にシリアル化するのに使用されます。
init_db
関数は、Flask アプリケーションでデータベースを初期化します。
def init_db(app):
db.init_app(app)
with app.app_context():
db.drop_all()
db.create_all()
# Create fake data
post1 = Post(title='Post The First', content='Content for the first post')
...
db.session.add(post1)
...
db.session.commit()
return db
db.init_app(app)
: Flask アプリケーションでデータベースを初期化します。with app.app_context()
: アプリケーションのコンテキストを作成します。db.drop_all()
: データベースのすべてのテーブルをドロップします。db.create_all()
: データベースのすべてのテーブルを作成します。- アプリケーションの偽データを作成します。
- データベースオブジェクトを返します。
/iris
エンドポイント
######################
# IRIS クエリ例 #
######################
@app.route('/iris', methods=['GET'])
def iris_query():
query = "SELECT top 10 * FROM %Dictionary.ClassDefinition"
rs = iris.sql.exec(query)
# Convert the result to a list of dictionaries
result = []
for row in rs:
result.append(row)
return jsonify(result)
このエンドポイントは、IRIS データベースでクエリを実行し、IRISAPP ネームスペースに存在する上位 10 個のクラスを返します。
/interop
エンドポイント
########################
# IRIS interop example #
########################
bs = Director.create_python_business_service('BS')
@app.route('/interop', methods=['GET', 'POST', 'PUT', 'DELETE'])
def interop():
rsp = bs.on_process_input(request)
return jsonify(rsp)
このエンドポイントは、IRIS の相互運用性フレームワークをテストするために使用されます。 ビジネスサービスオブジェクトを作成し、それを Flask アプリケーションにバインドします。
注: bs
オブジェクトは有効な状態を維持するために、リクエストの範囲外にある必要があります。
bs = Director.create_python_business_service('BS')
: 'BS' というビジネスサービスオブジェクトを作成します。rsp = bs.on_process_input(request)
: リクエストオブジェクトを引数としてビジネスサービスオブジェクトのon_process_input
メソッドを呼び出します。
/posts
エンドポイント
############################
# CRUD operations posts #
############################
@app.route('/posts', methods=['GET'])
def get_posts():
posts = Post.query.all()
return jsonify(posts)
@app.route('/posts', methods=['POST'])
def create_post():
data = request.get_json()
post = Post(title=data['title'], content=data['content'])
db.session.add(post)
db.session.commit()
return jsonify(post)
@app.route('/posts/<int:id>', methods=['GET'])
def get_post(id):
...
このエンドポイントは、Post
オブジェクトで CRUD 操作を実行するために使用されます。
dataclasses
モジュールにより、Post
オブジェクトは簡単に JSON にシリアル化できます。
以下では、すべての投稿を取得する sqlalchemy の query
メソッドと、新しい投稿を作成するための add
と commit
メソッドを使用しています。
/comments
エンドポイント
############################
# CRUD operations comments #
############################
@app.route('/comments', methods=['GET'])
def get_comments():
comments = Comment.query.all()
return jsonify(comments)
@app.route('/comments', methods=['POST'])
def create_comment():
data = request.get_json()
comment = Comment(content=data['content'], post_id=data['post_id'])
db.session.add(comment)
db.session.commit()
return jsonify(comment)
@app.route('/comments/<int:id>', methods=['GET'])
def get_comment(id):
...
このエンドポイントは、Comment
オブジェクトで CRUD 操作を実行するために使用されます。
Comment
オブジェクトは外部キーによって Post
オブジェクトにリンクされます。
トラブルシューティング
スタンドアロンモードで Flask アプリケーションを実行する方法
以下のコマンドを使用して、いつでもスタンドアロンの Flask アプリケーションを実行できます。
python3 /irisdev/app/community/app.py
注: このコマンドを実行するには、コンテナー内にいる必要があります。
docker exec -it iris-flask-template-iris-1 bash
IRIS でアプリケーションを再起動する
DEBUG
モードでアプリケーションに複数の呼び出しを行うと、変更はアプリケーションに反映されます。
IRIS 管理ポータルへのアクセス方法
http://localhost:53795/csp/sys/UtilHome.csp
に移動すると、IRIS 管理ポータルにアクセスできます。
このテンプレートをローカルで実行する
これには、マシンに IRIS がインストールされている必要があります。
次に、IRISAPP
というネームスペースを作成する必要があります。
要件をインストールします。
IoP のインストール:
#init iop
iop --init
# load production
iop -m /irisdev/app/community/interop/settings.py
# start production
iop --start Python.Production
セキュリティポータルでアプリケーションを構成します。