Python 官方文档:入门教程 => 点击学习
目录一、安装 Fastapi 和uvicorn二、创建 FastAPI 应用程序三、启动FastAPI 应用程序四、测试五、问题一、安装 FastAPI 和uvicorn
可以使用 pip 命令进行安装:
pip install fastapi uvicorn
例如 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 模型对象。
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` 服务器时,它会监视应用程序代码的更改,并在代码更改时自动重新加载服务器,以便不必手动重新启动服务器。
到此这篇关于使用python Fast API发布API服务的文章就介绍到这了,更多相关Python Fast API发布API服务内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 使用PythonFastAPI发布API服务的过程详解
本文链接: https://www.lsjlt.com/news/211182.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0