推薦FastApi不翩,這兩年異軍突起的網(wǎng)紅web框架,適合新手快速入門器钟。
總的來說妙蔗,F(xiàn)astAPI有三個(gè)優(yōu)點(diǎn):快、簡(jiǎn)昙啄、強(qiáng)寸五。
它的自我標(biāo)簽就是:FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
為什么說快梳杏、簡(jiǎn)、強(qiáng)呢?
首先叭莫,F(xiàn)astApi利用異步和輕量級(jí)的特點(diǎn)烁试,而且使用強(qiáng)類型减响,大大提升了性能郭怪,甚至可以媲美GO和NodeJS鄙才;其次能快速編程促绵、人為bug少、調(diào)試成本低浓冒、設(shè)計(jì)簡(jiǎn)單尖坤,使得web搭建速度能提升2-3倍,很適合新手去操作场梆。
它和Django相比有哪些異同點(diǎn)纯路?
和Django相比,F(xiàn)astAPI 是一個(gè)輕量級(jí)的 Web 框架顶岸。
Django 是 battery included,雖然配置麻煩萍桌,但默認(rèn)就帶了許多功能,包括很好用的 ORM恃逻、migration 工具藕施,也包括很多安全方面的中間件等等,還有比如模板系統(tǒng)矛市、靜態(tài)資源管理系統(tǒng)等等诲祸,對(duì)于一般的業(yè)務(wù)網(wǎng)站來說而昨,Django 是開箱即用的歌憨。
FastAPI 則非常輕量墩衙,它本身什么都不帶,沒有 ORM心铃、沒有 migration籽懦,沒有中間件暮顺,什么都沒有。這是缺點(diǎn)也是有優(yōu)點(diǎn)羽氮。
案例:
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}
運(yùn)行服務(wù)器
$ 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.
進(jìn)入http://127.0.0.1:8000/docs
會(huì)看到自動(dòng)生成的交互式 API 文檔
學(xué)習(xí)文檔:https://fastapi.tiangolo.com
GIthub地址:https://github.com/tiangolo/fastapi