fastapi部署服务

安装

pip install fastapi uvicorn

创建一个 FastAPI 应用,例如 main.py:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class RequestBody(BaseModel):
    content: str

@app.post("/process/")
async def process_string(request_body: RequestBody):
    # 这里可以对传来的字符串进行任意处理
    processed_content = request_body.content.upper()  # 示例:将字符串转为大写
    return {"processed_content": processed_content}

运行服务

uvicorn main:app --reload

(也可以在main中添加uvicorn.run(app, host='0.0.0.0', port=8012, workers=1),直接python main.py)
这将启动一个在本地运行的服务,默认情况下会运行在 http://127.0.0.1:8000
使用 curl 发送请求
现在你可以使用 curl 来向这个服务发送请求。请求内容是一串字符串。

这是一个示例请求:

curl -X POST "http://127.0.0.1:8000/process/" -H "Content-Type: application/json" -d '{"content": "hello, world"}'

解释下这个 curl 命令:

-X POST: 指定请求方法为 POST。
"http://127.0.0.1:8000/process/": 指定服务的 URL。
-H "Content-Type: application/json": 设置请求头的 Content-Type 为 application/json。
-d '{"content": "hello, world"}': 设置请求体数据,发送的内容是一串 JSON 字符串。

其他参考
https://zhuanlan.zhihu.com/p/678409211
https://zhuanlan.zhihu.com/p/696809583
https://fastapi.tiangolo.com/zh/tutorial/body/

posted @ 2024-07-05 15:45  Link_Z  阅读(1)  评论(0编辑  收藏  举报