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/

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)
  • 启动方式2:
# 默认端口启动
uvicorn main:app --reload
# 指定端口启动
uvicorn main:app --host '0.0.0.0' --port 8000 --reload
  • 启动方式3:
# 前两个都是阻塞式的,并且在控制台关闭之后,程序也就关闭了。使用gunicron完成启动
gunicorn main:app -b 0.0.0.0:8000  -w 4 -k uvicorn.workers.UvicornH11Worker --daemon

3、FastAPI编写POST请求

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

from pydantic import BaseModel

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

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

4、服务端完整版代码

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

:copyright: (c) 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)

5、客户端完整版代码

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

:copyright: (c) 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)

6、异步服务

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

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

:copyright: (c) 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)

你可能感兴趣的:(服务部署,python,服务器,linux)