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

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

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

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

pip install fastapi uvicorn

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

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

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)

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命令来运行这两个微服务:

uvicorn user_service:app --host 0.0.0.0 --port 8000 --reload

在这里插入图片描述

uvicorn order_service:app --host 0.0.0.0 --port 8001 --reload

在这里插入图片描述

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

微服务通信:

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

pip install httpx

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

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,实际的微服务架构可能涉及到更多的复杂性,如服务注册与发现、负载均衡、安全性等。

相关推荐

  1. python 简单demo

    2023-12-08 17:14:04       6 阅读
  2. Python基于 BaseHTTPRequestHandler 创建简单Web服务

    2023-12-08 17:14:04       17 阅读
  3. 使用Python创建一个简单Discord机器人

    2023-12-08 17:14:04       33 阅读
  4. 使用Python实现简单Web服务器

    2023-12-08 17:14:04       18 阅读
  5. Python实现简单Web服务器

    2023-12-08 17:14:04       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-08 17:14:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-08 17:14:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-08 17:14:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-08 17:14:04       20 阅读

热门阅读

  1. 【android开发-20】android中notification的用法讲解

    2023-12-08 17:14:04       30 阅读
  2. [python高级编程]:01-数据结构

    2023-12-08 17:14:04       42 阅读
  3. 机器学习算法汇总--GBDT、XGBoost等

    2023-12-08 17:14:04       40 阅读
  4. c++的排序算法

    2023-12-08 17:14:04       29 阅读
  5. [linux] git lfs install 安装lfs

    2023-12-08 17:14:04       38 阅读
  6. redis的工具类详细

    2023-12-08 17:14:04       30 阅读