Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] new example module #9

Merged
merged 4 commits into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 6 additions & 24 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
# LastEditors: 宁静致远 [email protected]
# LastEditTime: 2024-02-16 22:15:25

"""
这里做一下重写,
"""

import fastapi
import os
import importlib
import logging
from config import settings

Expand All @@ -18,25 +20,5 @@

# include services

services_path='services'
if not os.path.exists(services_path):
logger.critical(f"{os.path.join(os.getcwd(),services_path)} 不存在")
raise

services = os.listdir(services_path)
for service in services:
try:
entrypoint = importlib.import_module(f"{services_path}.{service}").entrypoint
matedata = entrypoint(settings)
logger.warn("#"*50+f"""
加载{service}
\t作者{matedata['Author']}
\t版本{matedata['Version']}
\t描述{matedata['Describe']}
"""+"#"*50)
application.include_router(matedata['Router'])
matedata['Init']()
except Exception as e:
logger.warn(f"加载{service}出错")
logger.warn(e)
if settings.get('debug',default=False):raise e
from services import createAPIRouter
application.include_router(createAPIRouter())
12 changes: 12 additions & 0 deletions services/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'''
Date: 2024-02-18 15:57:15
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 15:59:59
'''
def createAPIRouter():
from fastapi import APIRouter
router = APIRouter()
from . import example_service2,example_service3
router.include_router(example_service2.createAPIRouter())
router.include_router(example_service3.createAPIRouter())
return router
47 changes: 0 additions & 47 deletions services/example-service1/__init__.py

This file was deleted.

22 changes: 22 additions & 0 deletions services/example_service1/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
每一个模块必须的文件:
- __init__.py
- router.py
- api.py


__init__.py必须提供的东西:
- entrypoint(settings: dict) -> dict
- init_router(settings: dict) -> fastapi.APIRouter
"""
from . import router
from . import api

def entrypoint(settings: dict):
return {
"Author": "Example <[email protected]>",
"Version": "0.0.1",
"Description": "Example Service 1",
"PublicRouter": router.router,
"API": api,
}
19 changes: 19 additions & 0 deletions services/example_service1/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
这个文件是必须的。

这个文件定义了对模块提供的API。

提供方式 **只能** 是对业务逻辑的 import, 不能进行其他处理。

----------------------------------------------
别的模块通过

```py
from services.example_service1.api imoprt API1, API2, ...
```

来使用这个模块提供的API。
这些对模块暴露的api在这里被定义。
"""

from .func import add, hlwd
29 changes: 29 additions & 0 deletions services/example_service1/func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
这里是功能文件, 也就是该service内部的业务逻辑, 不管你怎么写, 分成不同的文件也可以。
"""

def plus(a, b):
"""
[tools] plus a and b
"""
return a + b


def add(a, b):
"""
add a and b

:param a: int
:param b: int

:return: int
"""
return plus(a, b)

def hlwd():
"""
say hello world

:return: str
"""
return "Hello World!"
103 changes: 103 additions & 0 deletions services/example_service1/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
'''
Date: 2024-02-18 15:41:17
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 15:51:41
'''
'''
Date: 2024-02-18 15:41:17
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 15:44:36
'''
"""
[该文件为必须文件]
router.py用于定义对外公开的api路由, 并提供一个router对象供__init__.py调用。

需要提供的东西:
- router: fastapi.APIRouter

----------------------------------------------------------
这里的函数应当能直接处理fastapi的调用。

一般该函数的内容:
1. Get Parameter 从http请求中取获取参数
2. Type Check 进行类型校验
3. Type Convert 进行类型转化
4. Process 调用api.py内的api函数。(提供给外部的api显然也得提供给内部)
5. Return 处理业务函数的返回值, reformat为json或其他格式, 返回给用户。

【注意】:为了保证代码简洁,这里的函数 **只能** 调用提供给业务逻辑函数。
"""

import fastapi

from . import api


router = fastapi.APIRouter(prefix="/example")

@router.get("/add")
def add(a:int,b:int):
"""
对func.add进行简单封装。

从参数中获取a和b, 做类型转化, 然后调用api.add。
**(为了代码整齐, 只能做这些)**

:param a: int
:param b: int

:return: int
"""
# Get parameter
# request = fastapi.Request()
# a = request.args.get("a")
# b = request.args.get("b")

# Type Check
if not isinstance(a, int) or not isinstance(b, int):
return {
"code": 1,
"msg": "Parameter Error",
"data": None
}

# Type Convert
a = int(a)
b = int(b)

# Process
ret = api.add(a, b)

# Return
return {
"code": 0,
"msg": "Success",
"data": ret
}

@router.get("/wrong")
def wrong_example(a:int,b:int,c:int):
"""
一个 **错误** 的例子。

这个函数调用了两个业务逻辑函数, 这是不允许的。

:return: int
"""
# Get parameter
# request = fastapi.Request()
# a = request.args.get("a")
# b = request.args.get("b")
# c = request.args.get("c")

# [Warning!] Call two business logic function
ret = api.add(a, b) + api.add(b, c)
# or
ret = api.add(api.add(a, b), c)

# Return
return {
"code": 0,
"msg": "Success",
"data": ret
}
9 changes: 9 additions & 0 deletions services/example_service2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'''
Date: 2024-02-18 15:54:04
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 16:02:04
'''

def createAPIRouter():
from . import router
return router.router
25 changes: 25 additions & 0 deletions services/example_service2/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'''
Date: 2024-02-18 15:54:04
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 16:02:42
'''
"""
这个文件是必须的。

这个文件定义了对模块提供的API。

提供方式 **只能** 是对业务逻辑的 import, 不能进行其他处理。

----------------------------------------------
别的模块通过

```py
from services.example_service1.api imoprt API1, API2, ...
```

来使用这个模块提供的API。
这些对模块暴露的api在这里被定义。
"""

def me(a):
return f"I'm e2. say {a}"
65 changes: 65 additions & 0 deletions services/example_service2/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'''
Date: 2024-02-18 15:41:17
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 16:10:16
'''
'''
Date: 2024-02-18 15:41:17
LastEditors: 宁静致远 [email protected]
LastEditTime: 2024-02-18 15:44:36
'''
"""
[该文件为必须文件]
router.py用于定义对外公开的api路由, 并提供一个router对象供__init__.py调用。

需要提供的东西:
- router: fastapi.APIRouter

----------------------------------------------------------
这里的函数应当能直接处理fastapi的调用。

一般该函数的内容:
1. Get Parameter 从http请求中取获取参数
2. Type Check 进行类型校验
3. Type Convert 进行类型转化
4. Process 调用api.py内的api函数。(提供给外部的api显然也得提供给内部)
5. Return 处理业务函数的返回值, reformat为json或其他格式, 返回给用户。

【注意】:为了保证代码简洁,这里的函数 **只能** 调用提供给业务逻辑函数。
"""

import fastapi

from . import api


router = fastapi.APIRouter(prefix="/example2")

@router.get("/add")
def add(a:int,b:int):
"""
对func.add进行简单封装。

从参数中获取a和b, 做类型转化, 然后调用api.add。
**(为了代码整齐, 只能做这些)**

:param a: int
:param b: int

:return: int
"""
# Get parameter
# request = fastapi.Request()
# a = request.args.get("a")
# b = request.args.get("b")


# Process
ret = a + b

# Return
return {
"code": 0,
"msg": "Success",
"data": ret
}
4 changes: 4 additions & 0 deletions services/example_service3/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

def createAPIRouter():
from . import router
return router.router
Loading