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)
### 回答1: 可以使用 Docker 部署 FastAPI 应用程序,也可以使用 uWSGI 或 Gunicorn 部署。在 Ubuntu 上,可以使用 Nginx 作为反向代理服务器来处理请求。具体的部署步骤可以参考 FastAPI 的官方文档。 ### 回答2: 在Ubuntu上部署FastAPI可以按照以下步骤进行: 1. 首先,确保已经安装了Python和pip。 ``` $ sudo apt update $ sudo apt install python3 $ sudo apt install python3-pip ``` 2. 创建一个新的虚拟环境(可选但推荐)。 ``` $ python3 -m venv myenv $ source myenv/bin/activate ``` 3. 安装FastAPI和uvicorn。 ``` $ pip3 install fastapi $ pip3 install uvicorn ``` 4. 编写一个FastAPI应用程序。 ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} ``` 5. 使用uvicorn运行应用程序。 ``` $ uvicorn main:app --host 0.0.0.0 --port 8000 ``` 这将在本地主机的8000端口上运行应用程序。 6. 若要在生产环境中使用FastAPI,您可以使用Gunicorn作为反向代理服务器。 ``` $ pip3 install gunicorn $ gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app ``` 这将在8000端口上运行FastAPI应用程序,并使用4个工作进程进行请求处理。 通过按照以上步骤,在您的Ubuntu服务器部署FastAPI应用程序应该是比较简单的。您可以根据您的需求进行进一步配置和调整。 ### 回答3: 要将FastAPI部署在Ubuntu上,可以按照以下步骤进行操作: 1. 确保Ubuntu系统已正确安装和配置。确保系统处于最新更新状态,可以通过运行`sudo apt update && sudo apt upgrade`命令来更新系统。 2. 安装Python和相关依赖。FastAPI是用Python编写的,因此需要在Ubuntu上安装Python及其相关依赖。在终端中运行以下命令安装Python: ``` sudo apt install python3-dev python3-pip ``` 3. 创建并激活虚拟环境(可选)。为了避免与系统中的其他Python软件包发生冲突,可以创建一个虚拟环境来安装和运行FastAPI。在终端中运行以下命令创建虚拟环境: ``` python3 -m venv myenv source myenv/bin/activate ``` 4. 安装FastAPI和其它软件包。在虚拟环境中运行以下命令来安装FastAPI和相应的依赖: ``` pip install fastapi[all] ``` 这将安装FastAPI及其所有附带的依赖,包括uvicorn作为默认的Web服务器。 5. 编写FastAPI应用程序。创建一个Python文件,例如`main.py`,使用FastAPI编写你的应用程序逻辑。例如,你可以创建一个简单的接口,显示一个Hello World消息。示例代码如下: ```python from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} ``` 6. 启动FastAPI应用程序。在终端中运行以下命令,启动FastAPI应用程序: ``` uvicorn main:app --host 0.0.0.0 --port 8000 ``` 这将使FastAPI应用程序在本地主机的8000端口上运行。 7. 在浏览器中测试。使用浏览器或任何HTTP客户端工具,访问`http://localhost:8000`,你将看到FastAPI应用程序返回的Hello World消息。 通过按照以上步骤,在Ubuntu上成功部署和运行FastAPI应用程序。这使你能够构建高性能、现代化的Web应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

风吹半夏灬

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值