【Python】FastAPI 使用python3.6+构建API的Web框架

现代、快速(高性能)的 Web 框架,用于构建基于 Python 的 API;基于 Starlette 和 Pydantic 库构建而成

官网:https://fastapi.tiangolo.com/

 

1、安装

# 对于生产环境,还需要一个ASGI服务器,如Uvicorn或Hypercorn 
# > pip install "uvicorn[standard]"
pip install fastapi
pip install uvicorn
pip install python-multipart

 

多种模板引擎

pip install  jinja2

 

2、创建 FastAPI 应用并运行 

方法1: 命令行启动fastapi

  IDE 编辑器中创建一个新的 Python 文件  [fastapi_main.py]

# -*- coding: UTF-8 -*-
from fastapi import FastAPI


app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

 

  在命令行中运行以下命令启动 FastAPI 应用

# 语法: uvicorn python文件名:FastAPI对象名 --reload
uvicorn fastapi_main:app --reload

 执行结果:

    

 

 FastAPI 将在本地启动一个服务器,并监听默认端口(8000)[http://127.0.0.1:8000/]

    

 

方法2:python直接运行

# -*- coding: UTF-8 -*-
import uvicorn
from fastapi import FastAPI


app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World~~"}


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8900)

 

 执行结果:

  

 

3、返回html页面 

# -*- coding: UTF-8 -*-
import uvicorn
from fastapi import FastAPI
from fastapi.responses import HTMLResponse


app = FastAPI()


@app.get("/index", response_class=HTMLResponse)
def read_root():
    html_file = open("../templates/html/index.html", 'r').read()
    return html_file


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8900)

 

 执行结果

    

    

4、GET、POST参数获取

# -*- coding: UTF-8 -*-
import uvicorn
from fastapi import Body
from fastapi import Query
from fastapi import FastAPI
from fastapi.responses import HTMLResponse


app = FastAPI()


# 路径参数:http://127.0.0.1:8900/index
@app.get("/index", response_class=HTMLResponse)
async def read_root():
    html_file = open("../templates/html/index.html", 'r').read()
    return html_file


# 路径参数:http://127.0.0.1:8900/name=zhangsan/age=12
@app.get("/name={n}/age={ag}")
async def server1(n, ag):
    return {
        "name": n,
        "age": ag,
    }


# get参数:http://127.0.0.1:8900/get/?name=lisi&age=23
@app.get("/get/")
async def server2(name=Query(None), age=Query(None)):
    return {
        "name": name,
        "age": age,
    }


# post参数:http://127.0.0.1:8900/post/
# post时body里设置:{"name":"wangerma","age":18}
@app.post("/post/")
async def server3(name=Body(None), age=Body(None)):
    return {
        "name": name,
        "age": age,
    }


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8900)

 

执行结果:

index 

   

路径参数获取

   

get参数获取 

   

 post 参数获取

   

 

 

 

  

posted @ 2023-10-12 17:28  Phoenixy  阅读(158)  评论(0编辑  收藏  举报