【Python】创建简单的Python微服务Demo与FastAPI

创建简单的Python微服务Demo与FastAPI

在微服务架构中,通过FastAPI框架创建一个简单的Python微服务Demo涉及多个步骤,包括定义服务、使用框架、进行通信等。在这篇文章中,我们将使用FastAPI框架创建两个简单的微服务,它们通过RESTful API进行通信。

首先,确保你已经安装了FastAPI和uvicorn,可以使用以下命令安装:

bash 复制代码
pip install fastapi uvicorn

然后,我们创建两个微服务:

微服务1:用户服务 (user_service.py)

python 复制代码
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id, "username": f"user{user_id}"}

微服务2:订单服务 (order_service.py)

python 复制代码
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/orders/{order_id}")
async def read_order(order_id: int):
    if order_id <= 0:
        raise HTTPException(status_code=400, detail="Invalid order ID")
    return {"order_id": order_id, "status": "processed"}

然后,我们可以使用uvicorn命令来运行这两个微服务:

bash 复制代码
uvicorn user_service:app --host 0.0.0.0 --port 8000 --reload
bash 复制代码
uvicorn order_service:app --host 0.0.0.0 --port 8001 --reload

现在,你有两个微服务在不同的端口上运行。user_service提供了获取用户信息的接口,而order_service提供了获取订单信息的接口。

微服务通信:

我们可以使用httpx库来模拟微服务之间的通信。确保你已经安装了它:

bash 复制代码
pip install httpx

然后,可以创建一个简单的脚本 (communication_demo.py) 来演示微服务之间的通信:

python 复制代码
import httpx

async def get_user(user_id):
    async with httpx.AsyncClient() as client:
        response = await client.get(f"http://127.0.0.1:8000/users/{user_id}")
        return response.json()

async def get_order(order_id):
    async with httpx.AsyncClient() as client:
        response = await client.get(f"http://127.0.0.1:8001/orders/{order_id}")
        return response.json()

async def main():
    user_info = await get_user(1)
    print("User Info:", user_info)

    order_info = await get_order(1001)
    print("Order Info:", order_info)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

在这个演示中,communication_demo.py 脚本通过调用 get_userget_order 函数来获取用户和订单信息。你可以运行这个脚本,看到微服务之间的通信效果。

这只是一个简单的微服务架构的Demo,实际的微服务架构可能涉及到更多的复杂性,如服务注册与发现、负载均衡、安全性等。

相关推荐
紫雾凌寒28 分钟前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
菜鸟阿达1 小时前
spring boot 2.7 + seata +微服务 降级失败问题修复
spring boot·后端·微服务
程序员杰哥1 小时前
测试用例详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
go54631584657 小时前
本地部署 GitHub 上的 Python 人脸识别项目
开发语言·python·github
FreakStudio8 小时前
手把手教你用 MicroPython 玩转幻尔串口舵机,代码+教程全公开
python·嵌入式·大学生·面向对象·技术栈·电子diy·电子计算机
tekin8 小时前
基于 Python 开发在线多人游戏服务器案例解析
服务器·python·游戏·在线多人游戏服务器
让学习成为一种生活方式10 小时前
libGL.so.1: cannot open shared object file: No such file or directory-linux022
linux·开发语言·python
java1234_小锋10 小时前
一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用
python·flask·flask3
图书馆钉子户10 小时前
from flask_session import Session 为什么是Session(app)这么用?
python·flask·mybatis
一只蜗牛儿10 小时前
Sherpa-ONNX:说话人识别与语音识别自动开启(VAD)+ Python API 完整指南
人工智能·python·语音识别