FastApi学习
1 分钟 3058 字 |
FastApi
安装
# 使用 FastAPI 需要 Python 版本大于等于 3.6
pip3 install fastapi
# uvicorn是基于 uvloop 和 httptools 构建的非常快速的 ASGI 服务器(异步网关协议)
pip3 install uvicorn
运行
main.py
# -*- coding:utf-8 -*-
from fastapi import FastAPI
import uvicorn
# 请求体类
from pydantic import BaseModel
from typing import Union
class Item(BaseModel):
name: str
# 参数有两种类型 :字符串或空
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
# 类似于 app = Flask(__name__)
app = FastAPI()
# 绑定路由和视图函数
@app.get("/")
def index():
return {"msg": "fastapi测试成功"}
# 异步 后面基本会用异步 速度快
@app.get("/A")
async def A():
return {"msg": "异步请求成功"}
# 同步
@app.get("/B")
def B():
return {"msg": "请求成功"}
### 路径参数
@app.get("/C/{item_id}")
def C(item_id):
return {"msg": item_id}
### 查询参数
@app.get("/D")
async def D(text:str):
return {"msg": text}
### 请求体参数
@app.get("/E")
async def D(item: Item):
return item
# 在 Windows 中必须加上 if __name__ == "__main__",否则会抛出 RuntimeError: This event loop is already running
if __name__ == "__main__":
# 启动服务,因为我们这个文件叫做 main.py,所以需要启动 main.py 里面的 app
# 第一个参数 "main:app" 就表示这个含义,然后是 host 和 port 表示监听的 ip 和端口
uvicorn.run("main:app", host="127.0.0.1", port=8000)
接口文档
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi import FastAPI, applications
def swagger_monkey_patch(*args, **kwargs):
return get_swagger_ui_html(
*args, **kwargs,
swagger_js_url='https://cdn.bootcdn.net/ajax/libs/swagger-ui/4.10.3/swagger-ui-bundle.js',
swagger_css_url='https://cdn.bootcdn.net/ajax/libs/swagger-ui/4.10.3/swagger-ui.css'
)
applications.get_swagger_ui_html = swagger_monkey_patch
参考
~ ~ The End ~ ~
分类标签:技术,python
文章标题:FastApi学习
文章链接:http://120.46.217.131:82/archives/22/
最后编辑:2022 年 9 月 16 日 16:43 By Yang
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
文章标题:FastApi学习
文章链接:http://120.46.217.131:82/archives/22/
最后编辑:2022 年 9 月 16 日 16:43 By Yang
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)