クイックAPI
ormarとfastapiの組み合わせは非常に簡単です。
起動時にデータベースに接続する以外に必要なのは、pydanticモデルをormarモデルに置き換えることだけです。
ここでは、非常に単純なサンプルアプリケーションコードを見つけることができます。
!!!警告この例では、データベースを作成したことを前提としています。そうでない場合は、データベースの初期化セクションにアクセスしてください。
!!!tip次のサンプル(すべての部分)は1つのファイルにまとめてください。
!!!note fastapiリクエストとレスポンスでormarモデルを使用する方法の詳細については、レスポンスとリクエストのドキュメントを参照してください。
クイックスタート
!!!メモ完全なクイックスタートスクリプトは、ギットハブリポジトリの例で見つけることができることに注意してください。
インポートと初期化
Fast APIライフサイクルを使用してプログラムの起動と終了を定義し、アプリケーションで使用します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | インポートリストの入力から、オプション
データベースのインポート
sqlalchemyをインポート
from fastapi import Fast API
インポートまたは
contextlibからasynccontextmanagerをインポート
from fastapi import Fast API
@asynccontextmanagerさん
ASync def lifespan(_: Fast API)->AsyncIterator[None]:
もしconfig. database.is_Connectedでない場合:
config. database.connect()を待ちます
利回り
もしconfig. Databaseが接続されている場合:
config. database.disconnect()を待ちます
base_ormar_config=ormar. OrmarConfig(ベースの設定
metadata=sqlalchemy. MetaData(),
データベース=データベース.データベース("sqlite:///test. db"),
)
app=Fast API(life pan=life pan(base_ormar_config))
|
!!!データベースへの接続の詳細については、fastapiドキュメントを参照してください
モデル定義
適切なフィールドを使用してormarモデルを定義します。
これらのモデルは、pydanticモデルの代わりに使用されます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | base_or_config=オーマコンフィグ(
メタデータ
データベース
)
class Category(ormar. Model):
or_config=base_or_config. copy(tablename="カテゴリ")
id: int=ormar.Integer(プライマリキー=True)
name: str=ormar.String(max_length=100)
class Item(ormar. Model):
base_or_config. copy()
id: int=ormar.Integer(プライマリキー=True)
name: str=ormar.String(max_length=100)
カテゴリー:オプション[カテゴリー]=ormar. ForeignKey(カテゴリー、nullable=True)
|
!!!ヒントモデルの定義については、モデルセクションを参照してください。
Fastapiエンドポイントの定義
ormarモデルがresponse_modelおよびリクエストパラメーターとしてどのように使用されるかに注意して、必要なエンドポイントを定義します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | @app. get("/items/",response_model=List[Item])
async def get_items():
items=await Item. object.select_関連("カテゴリ").all()
アイテムを返す
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
Waititem.save()
アイテムを返す
@app.post("/カテゴリー/", response_model=カテゴリー)
async def create_category(category: Category):
Waitcategory.save()
戻るカテゴリー
@app. put("/items/{item_id}")
async def get_item(item_id: int,item:Item):
item_db=await Item. object.get(pk=item_id)
return await item_db. update(**item.model_dump())
@app. delete("/items/{item_id}")
async def delete_item(item_id: int,item:Item=None):
ifアイテム:
リターン {"deleted_rows": await item.delete()}
item_db=await Item. object.get(pk=item_id)
リターン {"deleted_rows": await item_db.delete()}
|
!!!note save()のようなormarモデルメソッドがfastapiによって初期化された後に直接使用できる方法に注意してください。
!!!注意:モデル(またはモデルのリスト)を直接返すことができます。fastapiはそれをjsonizeします
アプリケーションのテスト
fastapiを実行する
このスクリプトを実行してfastapi swaggerを使用したい場合は、まずuvicornをインストールしてください
pipでuvicornをインストールする
fastapiを起動します。
uvicorn <filename_without_extension>:app --reload
これで、ブラウザ(デフォルトではfastapiアドレスは127.0.0.1:8000/docs)に移動してapiを使用できます。
!!!情報fastapiドキュメントでfastapiの実行に関する詳細を読むことができます。
テストにpytestを使用する
ここでは、すべてが期待どおりに機能することを証明するサンプルテストを紹介します。
必ず最初にテーブルを作成してください。pytestを使用している場合は、固定デバイスを使用できます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 | @pytest. fix(autouse=True,scope="module")
def create_test_database():
engine=sqlalchemy. create_engine(DATABASE_URL)
metadata. create_all(エンジン)
利回り
metadata. drop_all(エンジン)
#ここでは、fastapiでormarの動作を確認するためのサンプルテストです。
starlette. testclientからTestClientをインポート
def test_all_endpoints():
TestClientは同期のみで、ここではasynsを使用しないでください。
client=TestClient(アプリ)
#手動でデータベースに接続する必要があることに注意してください
#または、テスト中にクライアントをコンテキストマネージャーとして使用する
クライアントをクライアントとして:
応答=client.post("/カテゴリ/", json={"name": "test cat"})
カテゴリー=response. json()
応答=client.post(
"/items/", json={"name": "test", "id": 1, "category": category}
)
item=Item(**response. json())
アサートitem.pkはなし
response=client. get("/items/")
items=[Item(**item)for item in response. json()]
assert items[0]==item
item.name="新しい名前"
response=client. put(f"/items/{item.pk}",json=item.model_dump())
assert response. json()==item.model_dump()
response=client. get("/items/")
items=[Item(**item)for item in response. json()]
assert items[0]. name=="新しい名前"
response=client. delete(f"/items/{item.pk}",json=item.model_dump())
assert response. json().get("delete_rows","__UNDEFINED__")!="__UNDEFINED__"
response=client. get("/items/")
item=response. json()
assert len(items)==0
|
!!!ヒントより多くのテストケースとormar/fastapiのテスト方法を確認するには、ギットハブリポジトリのテストディレクトリを参照してください
!!!情報fastapiドキュメントでfastapiのテストの詳細を読むことができます。