Fast API

16999 ワード

Fast API

  • Starletteフレームワークに基づいて、
  • 非同期APIサーバをサポート
  • はPydanticライブラリと互換性があり、データ検証
  • をサポートする.
  • OpenAPIサポートによる自動生成Swig
  • 性能面ではノードやGoに相当する高性能
  • Starletteは他のPython Webフレームワークであり、Sanic、Flask、Djangoなどに比べて楽で強力なASGIフレーム/ツールキットです.fastapiはStaletteを1回だけ迂回するため、Staletteを直接使用するよりもパフォーマンスが低下するに違いありませんが、開発速度を速めるなど、メリットが相殺される可能性があります.スターレットが強力な  uvicornを使用しているからです.uvicornはuvloopとhttptoolsを使用した超高速ASGIサーバです.uvloopの性能の秘密はlibuvとCythonにある.fastapiがStarletteよりもパフォーマンスが悪いように、Starleteはuvicornを直接使用するよりも多くのコードを実行するため、速度が遅くなります.しかし,PATHベースのルーティングなどのツールを提供して簡単なWebアプリケーションを構築するため,生産性の面でより大きな助けとなる.
    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と同じ非同期処理速度が楽しめます.

    特長

  • https://github.com/tiangolo/fastapi
  • fast to code:機能開発速度は約200%から300%に向上した.
  • 減少
  • bug:人為的な誤りは約40%減少
  • 直感:優れたエディタサポート.すべての場所で自動的に完了します.デバッグ時間が少なくなります.
  • easy:使いやすく、勉強しやすいように設計されています.ドキュメントの読み取り時間が少なくなります.
  • https://fastapi.tiangolo.com/ko/
  • short:コード重複を最小化します.各パラメータが宣言する複数の機能.小さなエラー.

  • パラメータタイプを指定できます.(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
  • robust:ドキュメントの自動化と導入が容易
  • FastAPIは自動的に生成され、SWAGファイルを定義する必要はありません.要求と応答部分はpydanticモデルを使用し、配置時に自動的にjson形式に変換され、Swigの要求と応答モデルに自動的にマッピングされます.
  • サーバを実行します.  /docs  接続urlを使用すると、以下に示すSwagger UIが作成されます.
  • 接続
  • /redocで生成できます.
  • の複雑なシーンを含むAPIでなければ、SWAG環境で完全にテストすることができる.
  • (Try it outを押してExcuseで実行)
  • 規格:API(完全互換)オープン規格:OpenAPI(以前はSwaggerと呼ばれていた)およびJSONアーキテクチャに基づく.
  • 設定

    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.
  • 非同期処理が必要な場合はasyncおよびawaitを使用します.非同期呼び出しが必要な関数をdefではなくasync defとして処理し、データベースクエリーやI/Oを処理する必要がある場所で関数呼び出しの場所で待機します.
  • @app.get("/")
    async def read_root():
      return {"hello":"world"}
  • FastAPIはuvicornによって提供される非同期イベントループを使用する.そして. run in executorでthreadpoolを使用して同期関数を処理します. つまり、スレッドプールがすでに存在します.したがって、Guniornを使用している場合は パフォーマンスを向上させるためにthreadをアクティブにすることはできません.  逆に、パフォーマンスが低下し、最悪の場合、コンテキストに安全でないコードが存在する場合、問題が発生する可能性があります。 .
  • @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.
  • この方法では、次のことができます.
  • Editor support, including:
  • Completion.
  • Type checks.
  • Validation of data:
  • Automatic and clear errors when the data is invalid.
  • Validation even for deeply nested JSON objects.
  • Conversion of input data: coming from the network to Python data and types. Reading from:
  • JSON.
  • Path parameters.
  • Query parameters.
  • Cookies.
  • Headers.
  • Forms.
  • Files.
  • Conversion of output data: converting from Python data and types to network data (as JSON):
  • Convert Python types ( strintfloatboollist , etc).
  • datetime  objects.
  • UUID  objects.
  • Database models.
  • ...and many more.
  • Automatic interactive API documentation, including 2 alternative user interfaces:
  • Swagger UI.
  • ReDoc.