Fast API
16999 ワード
Fast API
Pydantic データの分析と検証に役立つライブラリです.入力タイプを宣言タイプに強制的に変換します(タイププロンプトを使用).
ValidationError
を使用してすべてのエラーを蓄積し、 ドキュメント化 あります.PydanticはParksingを助けているだけで、 Validation Check用のライブラリではありません.aのタイプがfloatに設定されている場合、値は str
に入っても float
Parsing できました.ただし、データ型がParsing不可の場合は、 Validation error
raise
.WSGI vs ASGI
WSGI
Webサーバとアプリケーションの間でミドルウェアとして機能し、WebサーバThe wsgiの操作コードが必要であり、アプリケーションにもwsgiの操作コードが必要であるクライアント-サーバモデルが技術的に適用されています.
Webサーバはアプリケーションのコードを直接読み取ることができないため、中間のミドルウェアはこれらのコードを読み取り、結果をユーザーに返す責任を負います.
ASGI
pythonはasyncioやcoroutineなどの非同期処理をサポートします.しかしながらwsgiは同期関数処理のみをサポートし,複数のタスクを同時に処理する能力が限られているため,Webサービスの大トラフィック処理を柔軟に処理することは困難である.
WebサービスではWeb socketなどを用いてリアルタイムチャットサービスを行うことができ,wsgiではこれらのサービスを実現することは困難である.(非同期キューなどの加速をうまく利用できれば、大トラフィックの処理を要求するサービスは実現できないが、追跡などのメンテナンスや基本的な実装は実現しにくい.)
そのため,最近ではdjango 3.0やFastAPIなどのフレームワークでasgiインタフェースが用いられている.
オペレーティングアーキテクチャから見ると、asgiはwsgiとあまり変わらないが、wsgiとは異なり、asgiはデフォルトで要求を非同期で処理し、wsgiがサポートしないwebsocketプロトコルとhttp 2.0をサポートする.
これらの代表的なasgiウェブappにはuvicornがあり、asgiベースのWebアプリケーションサーバとしてuvloopを内蔵するモジュールが使用されている.uvloopでは、uvはlibuv、すなわちjavascript v 8で使用されるすべての非同期を使用します.
asgiはCythonをベースにC++言語で記述されており,非常に高速でlibuvを用いて非同期処理を行うためnodeである.jsと同じ非同期処理速度が楽しめます.
特長
パラメータタイプを指定できます.(Python typeヒント)
したがって、タイプチェックを行い、データを自動的に検証し、エラーを自動的に生成できます.
from typing import List, Dict
from datetime import date
from pydantic import BaseModel
# Declare a variable as a str
# and get editor support inside the function
def main(user_id: str):
return user_id
# A Pydantic model
class User(BaseModel):
id: int
name: str
joined: date
/docs
接続urlを使用すると、以下に示すSwagger UIが作成されます.設定
pip install fastapi
pip install uvicon[standard]
//서버 실행 localhost:8000에서 확인 가능
uvicorn main:app --reload
main: the file main.py (the Python "module").
app: the object created inside of main.py with the line app = FastAPI().
--reload: make the server restart after code changes. Only do this for development.
뒤쪽에 붙은 --reload 옵션은 hot reloading 기능으로 소스 코드가 수정되면 서버를 바로 재시작하는
기능으로 개발 환경에서 활용하면 좋다.
きほんコード
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"hello":"world"}
@app.get("/items/{item_id}")
def read_item(item_id:int, q:Optional[str]=None):
return{"item_id":item_id, "q":q}
Receives HTTP requests in the paths / and /items/{item_id}.
Both paths take GET operations (also known as HTTP methods).
The path /items/{item_id} has a path parameter item_id that should be an int.
The path /items/{item_id} has an optional str query parameter q.
@app.get("/")
async def read_root():
return {"hello":"world"}
@app.put("/items/{item_id}")
def update_item(item_id:int, item:Item):
return { "item_name" : item.name, "item_id" : item_id }
//item 타입이 지정되어 있기 때문에 editor에서 auto-complete이 가능하다.
/docs로 접속 후 try it out 을 통해 parameter를 넣어주어 테스트한다.
Validate that there is an item_id in the path for GET and PUT requests.
Validate that the item_id is of type int for GET and PUT requests.
If it is not, the client will see a useful, clear error.
Check if there is an optional query parameter named q (as in http://127.0.0.1:8000/items/foo?q=somequery) for GET requests.
As the q parameter is declared with = None, it is optional.
Without the None it would be required (as is the body in the case with PUT).
For PUT requests to /items/{item_id}, Read the body as JSON:
Check that it has a required attribute name that should be a str.
Check that it has a required attribute price that has to be a float.
Check that it has an optional attribute is_offer, that should be a bool, if present.
All this would also work for deeply nested JSON objects.
Convert from and to JSON automatically.
Document everything with OpenAPI, that can be used by:
Interactive documentation systems.
Automatic client code generation systems, for many languages.
Provide 2 interactive documentation web interfaces directly.
str
, int
, float
, bool
, list
, etc). datetime
objects. UUID
objects. Reference
この問題について(Fast API), 我々は、より多くの情報をここで見つけました https://velog.io/@zoeyul/Fast-APIテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol