推薦FastApi,這兩年異軍突起的網紅web框架,適合新手快速入門。
總的來說,FastAPI有三個優點:快、簡、強。
它的自我標簽就是:FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
為什么說快、簡、強呢?
首先,FastApi利用異步和輕量級的特點,而且使用強類型,大大提升了性能,甚至可以媲美GO和NodeJS;其次能快速編程、人為bug少、調試成本低、設計簡單,使得web搭建速度能提升2-3倍,很適合新手去操作。
它和Django相比有哪些異同點?
和Django相比,FastAPI 是一個輕量級的 Web 框架。
Django 是 battery included,雖然配置麻煩,但默認就帶了許多功能,包括很好用的 ORM、migration 工具,也包括很多安全方面的中間件等等,還有比如模板系統、靜態資源管理系統等等,對于一般的業務網站來說,Django 是開箱即用的。
FastAPI 則非常輕量,它本身什么都不帶,沒有 ORM、沒有 migration,沒有中間件,什么都沒有。這是缺點也是有優點。
案例:
main.py
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}
運行服務器
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
會看到自動生成的交互式 API 文檔
學習文檔:https://fastapi.tiangolo.com
GIthub地址:https://github.com/tiangolo/fastapi