fastapi中实现多个路由请求

大家伙,我是雄雄,欢迎关注微信公众号:雄雄的小课堂。

前言

最近在写机器人相关的接口,顺手学了学python,发现这是个好东西,写代码效率比java要高很多,比如写个词云呀,写个回调呀,或者写个数据分析等等,都很方便。

今天,顺便在此记录一下,在使用fastapi的时候,创建多个文件,多个路由的问题。

一、创建新类api_sys.py

比如,我们这个类,就是一个崭新的路由,我们调用该类中的接口时,路由地址为:你的ip/路由/接口名,那么,我们来看看如何实现。

python 复制代码
# 引入依赖
from fastapi import APIRouter


router = APIRouter()

## 创建类,接收接口传递的json数据
class WechatDto(BaseModel):
    msg: str = None  # 消息内容
    tag: int = None  # 消息类型,例如:0表示发送文字,1表示发送图片等
    finalFromWxid: str = None  # 如果是群消息,发送消息的人的微信ID
    finalFromNick: str = None  # 如果是群消息,发送消息的人的微信ID
    fromWxid: str = None  # 发送消息的人的微信ID,如果是好友则为好友的wxid
    fromNick: str = None  # 发送消息的人的昵称,如果是好友则为好友的昵称
    memberCount: int = None  # 如果是群消息,群成员的数量;如果是好友消息则为空
    time: str = None  # 发送时间
    msgSource: int = None  # 发送消息的来源,0表示别人发送,1表示自己发送
    atList: list = []  # 艾特的人列表,通常是一个包含微信ID的列表

    # 创建get方法
    def get(self, param):
        return getattr(self, param)

# 微信机器人自定义接口
@router.post("/receive_message")
def receive_message(wechat: WechatDto):
    # 获取消息
    msg = wechat.msg
    # 获取用户
    finalFromWxid = wechat.finalFromWxid
    # 获取需要发送的群
    fromWxid = wechat.fromWxid
    finalFromNick = wechat.finalFromNick
    user_nick_list = [finalFromNick]
    user_name_list = [finalFromWxid]
    result = ''
    if msg.find("小助手") != -1:
        result = jiadian(msg, fromWxid, user_nick_list, user_name_list)
    return result

注意,关键代码就这几行:

python 复制代码
from fastapi import APIRouter
router = APIRouter()
@router.post("/receive_message")

然后,我们在main.py中引入这个路由类:

python 复制代码
from fastapi import FastAPI
# 导入依赖
from api.api_sys import router as api_sys_router

app = FastAPI()
# 添加前缀,例如
app.include_router(api_sys_router, prefix="/api")

其余就是你别的代码了,接下来,我们可以使用apipost来调用一下该接口,调用地址为:127.0.0.1:7552/api/receive_message,然后再body中该怎么传参就怎么传参,我这边传参是个json,就不在这里展示了。

创建第二个类api_huidiao.py

为了给大家能够跟清晰的展示,多个路由的概念,我们可以再创建一个类,继续当做一个路由,走走流程:

python 复制代码
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional, List
from fastapi import APIRouter

app = FastAPI()

huidiao_router = APIRouter()


class CallBackDataEntity(BaseModel):
    port: Optional[int] = None
    pid: Optional[int] = None
    wxid: Optional[str] = None
    wxNum: Optional[str] = None
    nick: Optional[str] = None
    device: Optional[str] = None
    phone: Optional[str] = None
    avatarUrl: Optional[str] = None
    country: Optional[str] = None
    province: Optional[str] = None
    city: Optional[str] = None
    email: Optional[str] = None
    qq: Optional[str] = None
    timeStamp: int
    fromType: int
    msgType: int
    msgSource: int
    fromWxid: str
    fromNick: str
    finalFromWxid: Optional[str] = None
    finalFromNick: Optional[str] = None
    atWidList: Optional[List[str]] = None
    silence: int
    membercount: int
    signature: Optional[str] = None
    msg: str


@huidiao_router.post("/receive_message_huidiao")
async def receive_message(data: CallBackDataEntity):
    print(f"接收到了回调消息,内容是:{data.dict()}")
    # 这里可以添加你的业务逻辑
    return {"message": "success"}


@huidiao_router.get("/test_api")
async def test_api():
    return {"message": "success"}

关键代码,还是那几行,只是名字有所不一样:

python 复制代码
from fastapi import APIRouter
huidiao_router = APIRouter()
@huidiao_router.post("/receive_message_huidiao")

下面是在main.py中新增的代码:

python 复制代码
from api.api_huidiao import huidiao_router as huidiao_router

app.include_router(huidiao_router, prefix="/api/huidiao")

接下来我们请求接口:http://127.0.0.1:7582/api/huidiao/test_api,即可。

相关推荐
陈苏同学18 分钟前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
唐家小妹21 分钟前
介绍一款开源的 Modern GUI PySide6 / PyQt6的使用
python·pyqt
羊小猪~~1 小时前
深度学习项目----用LSTM模型预测股价(包含LSTM网络简介,代码数据均可下载)
pytorch·python·rnn·深度学习·机器学习·数据分析·lstm
Marst Code1 小时前
(Django)初步使用
后端·python·django
985小水博一枚呀1 小时前
【对于Python爬虫的理解】数据挖掘、信息聚合、价格监控、新闻爬取等,附代码。
爬虫·python·深度学习·数据挖掘
立秋67892 小时前
Python的defaultdict详解
服务器·windows·python
萧鼎2 小时前
Python第三方库选择与使用陷阱避免
开发语言·python
Indigo_code2 小时前
【数据结构】【链表代码】合并有序链表
数据结构·windows·链表
暮雪倾风2 小时前
【WPF开发】超级详细的“文件选择”(附带示例工程)
windows·wpf
白拾2 小时前
使用Conda管理python环境的指南
开发语言·python·conda