記事
· 2025年3月27日 8m read

Iris における FastAPI アプリケーションの実行

fastapi_logo

説明

これは、ネイティブウェブアプリケーションとして IRIS にデプロイできる FastAPI アプリケーションのテンプレートです。

インストール

  1. リポジトリをクローンする
  2. 仮想環境を作成する
  3. 要件をインストールする
  4. docker-compose ファイルを実行する
git clone
cd iris-fastapi-template
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
docker-compose up

使用法

ベース URL は http://localhost:53795/fastapi/ です。

エンドポイント

  • /iris - IRISAPP ネームスペースに存在する上位 10 個のクラスを持つ JSON オブジェクトを返します。
  • /interop - IRIS の相互運用性フレームワークをテストするための ping エンドポイント。
  • /posts - Post オブジェクトの単純な CRUD エンドポイント。
  • /comments - Comment オブジェクトの単純な CRUD エンドポイント。

このテンプレートからの開発方法

WSGI 導入記事をご覧ください: wsgiサポートの概要

概要: セキュリティポータルで DEBUG フラグをトグルすると、開発作業の過程で変更内容がアプリケーションに反映されるようになります。

コードの説明

app.py

これは FastAPI アプリケーションのメインのファイルです。 FastAPI アプリケーションとルートが含まれます。

from fastapi import FastAPI, Request

import iris

from grongier.pex import Director

# import models
from models import Post, Comment, init_db
from sqlmodel import Session,select

app = FastAPI()

# create a database engine
url = "iris+emb://IRISAPP"
engine = init_db(url)
  • from fastapi import FastAPI, Request - FastAPI クラスト Request クラスをインポートします。
  • import iris - IRIS モジュールをインポートします。
  • from grongier.pex import Director: Flask アプリを IRIS 相互運用性フレームワークにバインドする Director クラスをインポートします。
  • from models import Post, Comment, init_db - モデルと init_db 関数をインポートします。
  • from sqlmodel import Session,select - Session クラスと sqlmodel モジュールの選択された関数をインポートします。
  • app = FastAPI() - FastAPI アプリケーションを作成します。
  • url = "iris+emb://IRISAPP" - IRIS ネームスペースの URL を定義します。
  • engine = init_db(url) - sqlmodel ORM のデータベースエンジンを作成します。

models.py

このファイルには、アプリケーションのモデルが含まれます。

from sqlmodel import Field, SQLModel, Relationship, create_engine

class Comment(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    post_id: int = Field(foreign_key="post.id")
    content: str
    post: "Post" = Relationship(back_populates="comments")

class Post(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    title: str
    content: str
    comments: list["Comment"] = Relationship(back_populates="post")

説明することは特にありません。外部キーとリレーションによる単なるモデルの定義です。

init_db 関数は、データベースエンジンの作成に使用されます。

def init_db(url):

    engine = create_engine(url)

    # create the tables
    SQLModel.metadata.drop_all(engine)
    SQLModel.metadata.create_all(engine)

    # initialize database with fake data
    from sqlmodel import Session

    with Session(engine) as session:
        # Create fake data
        post1 = Post(title='Post The First', content='Content for the first post')
        ...
        session.add(post1)
        ...
        session.commit()

    return engine
  • engine = create_engine(url) - データベースエンジンを作成します。
  • SQLModel.metadata.drop_all(engine) - すべてのテーブルをドロップします。
  • SQLModel.metadata.create_all(engine) - すべてのテーブルを作成します。
  • with Session(engine) as session: - データベースを操作するためのセッションを作成します。
  • post1 = Post(title='Post The First', content='Content for the first post') - Post オブジェクトを作成します。
  • session.add(post1) - Post オブジェクトをセッションに追加します。
  • session.commit() - 変更内容をデータベースにコミットします。
  • return engine - データベースエンジンを返します。

/iris エンドポイント

######################
# IRIS Query example #
######################

@app.get("/iris")
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 result
  • @app.get("/iris") - /iris エンドポイントの GET ルートを定義します。
  • query = "SELECT top 10 * FROM %Dictionary.ClassDefinition" - IRIS ネームスペースで上位 10 個のクラスを取得するクエリを定義します。
  • rs = iris.sql.exec(query) - クエリを実行します。
  • result = [] - 結果を保存する空のリストを作成します。
  • for row in rs: - 結果セットを反復処理します。
  • result.append(row) - 結果リストを行にアペンドします。
  • return result - 結果リストを返します。

/interop エンドポイント

########################
# IRIS interop example #
########################
bs = Director.create_python_business_service('BS')

@app.get("/interop")
@app.post("/interop")
@app.put("/interop")
@app.delete("/interop")
def interop(request: Request):

    rsp = bs.on_process_input(request)

    return rsp

  • bs = Director.create_python_business_service('BS') - Python ビジネスサービスを作成します。
    • ビジネスサービスの複数のインスタンスを防止するために、ルート定義の外に作成する必要があります。
  • @app.get("/interop") - /interop エンドポイントの GET ルートを定義します。
  • @app.post("/interop") - /interop エンドポイントの POST ルートを定義します。
  • ...
  • def interop(request: Request): - ルートハンドラーを定義します。
  • rsp = bs.on_process_input(request) - ビジネスサービスの on_process_input メソッドを呼び出します。
  • return rsp - レスポンスを返します。

/posts エンドポイント

############################
# CRUD operations posts    #
############################

@app.get("/posts")
def get_posts():
    with Session(engine) as session:
        posts = session.exec(select(Post)).all()
        return posts

@app.get("/posts/{post_id}")
def get_post(post_id: int):
    with Session(engine) as session:
        post = session.get(Post, post_id)
        return post

@app.post("/posts")
def create_post(post: Post):
    with Session(engine) as session:
        session.add(post)
        session.commit()
        return post

このエンドポイントは、Post オブジェクトで CRUD 操作を実行するために使用されます。

説明することは特にありません。すべての投稿を取得し、ID で投稿を取得し、投稿を作成するためのルートの定義です。

すべては sqlmodel ORM を使って行われます。

/comments エンドポイント

############################
# CRUD operations comments #
############################


@app.get("/comments")
def get_comments():
    with Session(engine) as session:
        comments = session.exec(select(Comment)).all()
        return comments

@app.get("/comments/{comment_id}")
def get_comment(comment_id: int):
    with Session(engine) as session:
        comment = session.get(Comment, comment_id)
        return comment

@app.post("/comments")
def create_comment(comment: Comment):
    with Session(engine) as session:
        session.add(comment)
        session.commit()
        return comment

このエンドポイントは、Comment オブジェクトで CRUD 操作を実行するために使用されます。

説明することは特にありません。すべてのコメントを取得し、ID でコメントを取得し、コメントを作成するためのルートの定義です。

すべては sqlmodel ORM を使って行われます。

トラブルシューティング

スタンドアロンモードで FastAPI アプリケーションを実行する方法

以下のコマンドを使用して、いつでもスタンドアロンの Flask アプリケーションを実行できます。

python3 /irisdev/app/community/app.py

注: このコマンドを実行するには、コンテナー内にいる必要があります。

docker exec -it iris-fastapi-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

セキュリティポータルでアプリケーションを構成します。

ディスカッション (0)1
続けるにはログインするか新規登録を行ってください