Python的哪個(gè)Web框架學(xué)習(xí)周期短,學(xué)習(xí)成本低?
知乎上有人問(wèn),Python的哪個(gè)Web框架學(xué)習(xí)周期短,學(xué)習(xí)成本低?
很多人推薦Flask,老牌輕量級(jí)web框架,確實(shí)是初學(xué)者的首選。這幾天我在Github上看到FastApi,覺(jué)得比Flask更輕量。
FastApi是這兩年異軍突起的網(wǎng)紅web框架,適合新手快速入門(mén)。。
總的來(lái)說(shuō),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.
為什么說(shuō)快、簡(jiǎn)、強(qiáng)呢?
- 首先,F(xiàn)astApi利用異步和輕量級(jí)的特點(diǎn),而且使用強(qiáng)類(lèi)型,大大提升了性能,甚至可以媲美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)站來(lái)說(shuō),Django 是開(kāi)箱即用的。
FastAPI 則非常輕量,它本身什么都不帶,沒(méi)有 ORM、沒(méi)有 migration,沒(méi)有中間件,什么都沒(méi)有。這是缺點(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