fastapi使用知识

前沿

FastAPI 是用来构建 API 服务的一个高性能框架。快!性能极高,可与 NodeJS, Go 媲美。
FastAPI(中文官方文档):https://fastapi.tiangolo.com/zh/

uvicorn是一个闪电般快速的ASGI服务器,基于uvloop和httptools构建。

步骤

1、安装依赖包(fastapi、uvicorn、gunicorn)

pip install fastapi -i https://pypi.douban.com/simple/
pip install uvicorn -i https://pypi.douban.com/simple/
pip install gunicorn -i https://pypi.douban.com/simple/

  
  
  • 1
  • 2
  • 3

2、测试并启动

  • 启动方式1:python fastapi_main.py
"""fastapi_main.py
~~~~~~~~~~~~~~
:copyright: (c) 2020 by Dingdang Cat
:modified: 2020-09-15
"""
import uvicorn
from fastapi import FastAPI

apps = FastAPI()

@apps.get("/")
async def root():
return { “message”: “Hello World”}

if name==main:
uvicorn.run(app=‘fastapi_main:apps’, host=“0.0.0.0”,port=8000,reload=True,debug=True)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 启动方式2:
# 默认端口启动
uvicorn main:app --reload
# 指定端口启动
uvicorn main:app --host '0.0.0.0' --port 8000 --reload

 
 
  • 1
  • 2
  • 3
  • 4
  • 启动方式3:
# 前两个都是阻塞式的,并且在控制台关闭之后,程序也就关闭了。使用gunicron完成启动
gunicorn main:app -b 0.0.0.0:8000  -w 4 -k uvicorn.workers.UvicornH11Worker --daemon

 
 
  • 1
  • 2

3、FastAPI编写POST请求

fastapi 定义请求体,需要从pydantic的BaseModel

from pydantic import BaseModel

 
 
  • 1

创建数据模型;然后,将你的数据模型声明为继承自 BaseModel 的类。
使用标准的 Python 类型来声明所有属性

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

 
 
  • 1
  • 2
  • 3
  • 4
  • 5

4、服务端完整版代码

"""fast_app.py
~~~~~~~~~~~~~~
本模块是fastapi算法服务的入口。

©️ © 2020 by Dingdang Cat
:modified: 2020-09-15
“”"
import requests
from fastapi import FastAPI, Request
from pydantic import BaseModel
from datetime import datetime
from typing import List, Dict, Set, Union, Text, Tuple, Optional

# 创建数据模型
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None

app = FastAPI()

@app.get("/")
async def root():
return ‘Hello World!’

@app.post("/algorithm/ner-tagging/")
async def fcao_predict(item: Item):
item_dict = item.dict()
name = item_dict[“name”]
description = item_dict[“description”]
price = item_dict[“price”]
tax = item_dict[“tax”]
hanshu(name, description, price, tax) # 实现某个功能的函数
return { “code”: 200, “msg”: “请求成功”, “data”: “”}

if name == main:
uvicorn.run(app)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

5、客户端完整版代码

"""test_api.py
~~~~~~~~~~~~~~

©️ © 2020 by Dingdang Cat
:modified: 2020-09-15
“”"
import requests
import json
import time

def ner_tagging(body):
“”“项目公文解析服务api测试”""
time1 = time.time()
ret = requests.post(“http://192.168.1.141:8000/algorithm/ner-tagging/”, json.dumps(body))
print(“发送post数据请求成功!”)
time2 = time.time()
print("ELAPSED: ", time2 - time1)
print(“RESULT:”, ret.json())

if name == main:
body={
“name”: “Foo”,
“description”: “An optional description”,
“price”: 45.2,
“tax”: 3.5
}
ner_tagging(body)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

6、异步服务

当你的计算为异步时,需要在本地开启callback服务用以接收返回结果

"""callback_service.py
~~~~~~~~~~~~~~
本模块主要提供接收计算后返回的结果.

©️ © 2020 by Dingdang Cat
:modified: 2020-09-16
“”"
import uvicorn
from fastapi import FastAPI, Request
from pydantic import BaseModel
from pprint import pprint

platform_app = FastAPI()

class Item(BaseModel):
elapsedTime: float = None
taskTime: str = None
results: dict = { }

@platform_app.post(’/callback-result’)
def callback_result(item: Item):
“”" 接收计算后返回的结果,对算法平台计算后返回的结果进行评测
“”"

item_dict = item.dict()
# 接收文本数据
calculate_time = item_dict[“elapsedTime”]
task_time = item_dict[“taskTime”]
documents = item_dict[“results”]
pprint(documents)
print(“回调发起时间:”, task_time)
print(“任务耗时%s” % round(calculate_time, 2))
print(“收到计算后返回的结果有 %d 条” % len(documents))
# 判断接收的数据是否为空
if not len(documents):
return { “err_code”: “1”,
“data”: “”,
“msg”: “No res received”}
return { “code”: “200”,
“data”: “”,
“msg”: “”}

if name == main:
uvicorn.run(app=“callback_service:platform_app”, host=“0.0.0.0”, port=9050, reload=True, debug=True)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图灵追慕者

您的支持是我写作分享最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值