大家伙,我是雄雄,欢迎关注微信公众号:雄雄的小课堂。
前言
最近在写机器人相关的接口,顺手学了学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
,即可。