安装
pip install fastapi[all]
pip install unicorn
基本使用(不能同时支持,get, post方法等要分开写)
from fastapi import FastAPI
app = FastAPI()
@app.get('/') # 点get就支持get请求
def read_root():
return {"hello":'world'}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app,host='127.0.0.1',port=8080)
模版渲染
fastapi本身是没有模版渲染功能的,需要你借助于第三方的模版工具
该框架默认情况下也是借助于jinja2来做模版渲染(flask也是使用jinja2, 如果用过flask, 默认是装过jinja2)
# 安装
pip install jinja2
# 基本使用
from starlette.requests import Request
from fastapi import FastAPI
from starlette.templating import Jinja2Templates
app = FastAPI()
# 挂载模版文件夹
tmp = Jinja2Templates(directory='templates')
@app.get('/')
async def ge