使用Python Fast API发布API服务的过程详解

作者:Tom 时间:2022-05-19 20:03:44 

一、安装 FastAPI 和uvicorn

可以使用 pip 命令进行安装:

pip install fastapi uvicorn

二、创建 FastAPI 应用程序

例如 main.py 文件:

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
   return {"item_id": item_id, "q": q}

@app.post("/items/")
def create_item(item: Item):
   return item

在这个例子中,创建了一个 FastAPI 应用程序,并定义了三个路由:`/`,`/items/{item_id}` 和 `/items/`。

`read_root()` 和 `read_item()` 路由使用 `@app.get()` 装饰器来定义 `GET` 请求处理程序,而

`create_item()` 路由使用 `@app.post()` 装饰器来定义 `POST` 请求处理程序。

这些路由返回不同的响应内容,包括 JSON 数据和 FastAPI 模型对象。

三、启动FastAPI 应用程序

uvicorn main:app --reload

在这个例子中,我们使用 `uvicorn` 命令来启动 FastAPI 应用程序,监听 `http://localhost:8000` 地址,并自动重新加载应用程序代码更改。如果您需要在其他端口上运行应用程序,可以使用 `--port` 参数来指定端口号。

四、测试

例如,使用 curl 或其他 HTTP 客户端向您的应用程序发送请求:

curl http://localhost:8000/
curl http://localhost:8000/items/5?q=somequery
curl -X POST http://localhost:8000/items/ -H "Content-Type: application/json" -d '{"name": "item name", "description": "item description"}'

五、问题

1、如果需要被其他机器调用,需要启动应用程序时指定host

如:uvicorn main:app --host 192.168.10.8  --port 8888 --reload

2、启动参数 reload的含义

使用 `--reload` 参数启动 `uvicorn` 服务器时,它会监视应用程序代码的更改,并在代码更改时自动重新加载服务器,以便不必手动重新启动服务器。

来源:https://blog.csdn.net/xu_guo_jie/article/details/130233874

标签:Python,Fast,API,API,服务
0
投稿

猜你喜欢

  • Python获取秒级时间戳与毫秒级时间戳的示例代码

    2022-05-05 22:13:00
  • python optparse模块使用实例

    2021-02-03 22:01:36
  • oracle SQL命令大全

    2009-07-02 11:55:00
  • Python机器学习之KNN近邻算法

    2022-05-12 23:14:17
  • 如何恢复MYSQL的ROOT口令

    2008-06-02 13:59:00
  • Python实现为PDF大文件批量去除水印

    2023-04-14 19:59:04
  • 浅谈视觉设计的准确性

    2007-09-18 17:59:00
  • 让IE8支持eWebEditor在线编辑器

    2010-02-28 10:36:00
  • 整理Python最基本的操作字典的方法

    2022-03-01 07:04:38
  • Python Learning 列表的更多操作及示例代码

    2022-11-15 01:05:33
  • 讲解SQL Server 2005数据库的同义词Bug

    2008-11-28 14:22:00
  • Go语言流程控制详情

    2023-10-16 13:16:24
  • oblog4.6转换ucenterHome1.5过程全记录,提供老用户无法登陆的补丁

    2009-10-29 12:04:00
  • Update 语句

    2009-06-22 12:52:00
  • Python+matplotlib实现堆叠图的绘制

    2023-07-21 17:38:35
  • Python线程之如何解决共享变量问题

    2023-08-27 16:15:56
  • 阿里妈妈广告牌制作规范

    2009-07-15 13:23:00
  • 服务端XMLHTTP(ServerXMLHTTP in ASP)基本应用(上)

    2008-11-11 12:49:00
  • MySQL的6种日志详解

    2008-12-18 14:36:00
  • phpstorm断点调试方法图文详解

    2023-05-30 01:06:40
  • asp之家 网络编程 m.aspxhome.com