Skip to content

Commit 57f898a

Browse files
insistencegitee-org
authored andcommitted
!19 RuoYi-Vue-FastAPI v1.5.1
Merge pull request !19 from insistence/develop
2 parents 4ee98e7 + 55c60db commit 57f898a

File tree

12 files changed

+72
-223
lines changed

12 files changed

+72
-223
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
<p align="center">
22
<img alt="logo" src="https://oscimg.oschina.net/oscnet/up-d3d0a9303e11d522a06cd263f3079027715.png">
33
</p>
4-
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">RuoYi-Vue-FastAPI v1.5.0</h1>
4+
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">RuoYi-Vue-FastAPI v1.5.1</h1>
55
<h4 align="center">基于RuoYi-Vue+FastAPI前后端分离的快速开发框架</h4>
66
<p align="center">
77
<a href="https://gitee.com/insistence2022/RuoYi-Vue-FastAPI/stargazers"><img src="https://gitee.com/insistence2022/RuoYi-Vue-FastAPI/badge/star.svg?theme=dark"></a>
88
<a href="https://github.com/insistence/RuoYi-Vue-FastAPI"><img src="https://img.shields.io/github/stars/insistence/RuoYi-Vue-FastAPI?style=social"></a>
9-
<a href="https://gitee.com/insistence2022/RuoYi-Vue-FastAPI"><img src="https://img.shields.io/badge/RuoYiVueFastAPI-v1.5.0-brightgreen.svg"></a>
9+
<a href="https://gitee.com/insistence2022/RuoYi-Vue-FastAPI"><img src="https://img.shields.io/badge/RuoYiVueFastAPI-v1.5.1-brightgreen.svg"></a>
1010
<a href="https://gitee.com/insistence2022/RuoYi-Vue-FastAPI/blob/master/LICENSE"><img src="https://img.shields.io/github/license/mashape/apistatus.svg"></a>
1111
<img src="https://img.shields.io/badge/python-≥3.9-blue">
1212
<img src="https://img.shields.io/badge/MySQL-≥5.7-blue">

ruoyi-fastapi-backend/.env.dev

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ APP_HOST = '0.0.0.0'
1010
# 应用端口
1111
APP_PORT = 9099
1212
# 应用版本
13-
APP_VERSION= '1.5.0'
13+
APP_VERSION= '1.5.1'
1414
# 应用是否开启热重载
1515
APP_RELOAD = true
1616
# 应用是否开启IP归属区域查询

ruoyi-fastapi-backend/.env.prod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ APP_HOST = '0.0.0.0'
1010
# 应用端口
1111
APP_PORT = 9099
1212
# 应用版本
13-
APP_VERSION= '1.5.0'
13+
APP_VERSION= '1.5.1'
1414
# 应用是否开启热重载
1515
APP_RELOAD = false
1616
# 应用是否开启IP归属区域查询

ruoyi-fastapi-backend/config/get_scheduler.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import json
22
from apscheduler.events import EVENT_ALL
3-
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
4-
from apscheduler.schedulers.background import BackgroundScheduler
3+
from apscheduler.executors.asyncio import AsyncIOExecutor
4+
from apscheduler.executors.pool import ProcessPoolExecutor
55
from apscheduler.jobstores.memory import MemoryJobStore
66
from apscheduler.jobstores.redis import RedisJobStore
77
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
8+
from apscheduler.schedulers.asyncio import AsyncIOScheduler
89
from apscheduler.triggers.cron import CronTrigger
10+
from asyncio import iscoroutinefunction
911
from datetime import datetime, timedelta
1012
from sqlalchemy.engine import create_engine
1113
from sqlalchemy.orm import sessionmaker
@@ -109,9 +111,9 @@ def __find_recent_workday(cls, day: int):
109111
)
110112
),
111113
}
112-
executors = {'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5)}
114+
executors = {'default': AsyncIOExecutor(), 'processpool': ProcessPoolExecutor(5)}
113115
job_defaults = {'coalesce': False, 'max_instance': 1}
114-
scheduler = BackgroundScheduler()
116+
scheduler = AsyncIOScheduler()
115117
scheduler.configure(jobstores=job_stores, executors=executors, job_defaults=job_defaults)
116118

117119

@@ -132,9 +134,7 @@ async def init_system_scheduler(cls):
132134
async with AsyncSessionLocal() as session:
133135
job_list = await JobDao.get_job_list_for_scheduler(session)
134136
for item in job_list:
135-
query_job = cls.get_scheduler_job(job_id=str(item.job_id))
136-
if query_job:
137-
cls.remove_scheduler_job(job_id=str(item.job_id))
137+
cls.remove_scheduler_job(job_id=str(item.job_id))
138138
cls.add_scheduler_job(item)
139139
scheduler.add_listener(cls.scheduler_event_listener, EVENT_ALL)
140140
logger.info('系统初始定时任务加载成功')
@@ -169,6 +169,10 @@ def add_scheduler_job(cls, job_info: JobModel):
169169
:param job_info: 任务对象信息
170170
:return:
171171
"""
172+
job_func = eval(job_info.invoke_target)
173+
job_executor = job_info.job_executor
174+
if iscoroutinefunction(job_func):
175+
job_executor = 'default'
172176
scheduler.add_job(
173177
func=eval(job_info.invoke_target),
174178
trigger=MyCronTrigger.from_crontab(job_info.cron_expression),
@@ -180,7 +184,7 @@ def add_scheduler_job(cls, job_info: JobModel):
180184
coalesce=True if job_info.misfire_policy == '2' else False,
181185
max_instances=3 if job_info.concurrent == '0' else 1,
182186
jobstore=job_info.job_group,
183-
executor=job_info.job_executor,
187+
executor=job_executor,
184188
)
185189

186190
@classmethod
@@ -191,6 +195,10 @@ def execute_scheduler_job_once(cls, job_info: JobModel):
191195
:param job_info: 任务对象信息
192196
:return:
193197
"""
198+
job_func = eval(job_info.invoke_target)
199+
job_executor = job_info.job_executor
200+
if iscoroutinefunction(job_func):
201+
job_executor = 'default'
194202
scheduler.add_job(
195203
func=eval(job_info.invoke_target),
196204
trigger='date',
@@ -203,7 +211,7 @@ def execute_scheduler_job_once(cls, job_info: JobModel):
203211
coalesce=True if job_info.misfire_policy == '2' else False,
204212
max_instances=3 if job_info.concurrent == '0' else 1,
205213
jobstore=job_info.job_group,
206-
executor=job_info.job_executor,
214+
executor=job_executor,
207215
)
208216

209217
@classmethod
@@ -214,7 +222,9 @@ def remove_scheduler_job(cls, job_id: Union[str, int]):
214222
:param job_id: 任务id
215223
:return:
216224
"""
217-
scheduler.remove_job(job_id=str(job_id))
225+
query_job = cls.get_scheduler_job(job_id=job_id)
226+
if query_job:
227+
scheduler.remove_job(job_id=str(job_id))
218228

219229
@classmethod
220230
def scheduler_event_listener(cls, event):

ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py

Lines changed: 4 additions & 187 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,18 @@
33
import os
44
import requests
55
import time
6-
import warnings
76
from datetime import datetime
87
from fastapi import Request
98
from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse
109
from functools import lru_cache, wraps
11-
from typing import Literal, Optional, Union
10+
from typing import Literal, Optional
1211
from user_agents import parse
13-
from module_admin.entity.vo.log_vo import LogininforModel, OperLogModel
14-
from module_admin.service.log_service import LoginLogService, OperationLogService
15-
from module_admin.service.login_service import LoginService
1612
from config.enums import BusinessType
1713
from config.env import AppConfig
1814
from exceptions.exception import LoginException, ServiceException, ServiceWarning
15+
from module_admin.entity.vo.log_vo import LogininforModel, OperLogModel
16+
from module_admin.service.log_service import LoginLogService, OperationLogService
17+
from module_admin.service.login_service import LoginService
1918
from utils.log_util import logger
2019
from utils.response_util import ResponseUtil
2120

@@ -201,188 +200,6 @@ async def wrapper(*args, **kwargs):
201200
return wrapper
202201

203202

204-
def log_decorator(
205-
title: str,
206-
business_type: Union[Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], BusinessType],
207-
log_type: Optional[Literal['login', 'operation']] = 'operation',
208-
):
209-
"""
210-
日志装饰器
211-
212-
:param title: 当前日志装饰器装饰的模块标题
213-
:param business_type: 业务类型(0其它 1新增 2修改 3删除 4授权 5导出 6导入 7强退 8生成代码 9清空数据)
214-
:param log_type: 日志类型(login表示登录日志,operation表示为操作日志)
215-
:return:
216-
"""
217-
warnings.simplefilter('always', category=DeprecationWarning)
218-
if isinstance(business_type, BusinessType):
219-
business_type = business_type.value
220-
warnings.warn(
221-
'未来版本将会移除@log_decorator装饰器,请使用@Log装饰器',
222-
category=DeprecationWarning,
223-
stacklevel=2,
224-
)
225-
226-
def decorator(func):
227-
@wraps(func)
228-
async def wrapper(*args, **kwargs):
229-
start_time = time.time()
230-
# 获取被装饰函数的文件路径
231-
file_path = inspect.getfile(func)
232-
# 获取项目根路径
233-
project_root = os.getcwd()
234-
# 处理文件路径,去除项目根路径部分
235-
relative_path = os.path.relpath(file_path, start=project_root)[0:-2].replace('\\', '.')
236-
# 获取当前被装饰函数所在路径
237-
func_path = f'{relative_path}{func.__name__}()'
238-
# 获取上下文信息
239-
request: Request = kwargs.get('request')
240-
token = request.headers.get('Authorization')
241-
query_db = kwargs.get('query_db')
242-
request_method = request.method
243-
operator_type = 0
244-
user_agent = request.headers.get('User-Agent')
245-
if 'Windows' in user_agent or 'Macintosh' in user_agent or 'Linux' in user_agent:
246-
operator_type = 1
247-
if 'Mobile' in user_agent or 'Android' in user_agent or 'iPhone' in user_agent:
248-
operator_type = 2
249-
# 获取请求的url
250-
oper_url = request.url.path
251-
# 获取请求的ip及ip归属区域
252-
oper_ip = request.headers.get('X-Forwarded-For')
253-
oper_location = '内网IP'
254-
if AppConfig.app_ip_location_query:
255-
oper_location = get_ip_location(oper_ip)
256-
# 根据不同的请求类型使用不同的方法获取请求参数
257-
content_type = request.headers.get('Content-Type')
258-
if content_type and (
259-
'multipart/form-data' in content_type or 'application/x-www-form-urlencoded' in content_type
260-
):
261-
payload = await request.form()
262-
oper_param = '\n'.join([f'{key}: {value}' for key, value in payload.items()])
263-
else:
264-
payload = await request.body()
265-
# 通过 request.path_params 直接访问路径参数
266-
path_params = request.path_params
267-
oper_param = {}
268-
if payload:
269-
oper_param.update(json.loads(str(payload, 'utf-8')))
270-
if path_params:
271-
oper_param.update(path_params)
272-
oper_param = json.dumps(oper_param, ensure_ascii=False)
273-
# 日志表请求参数字段长度最大为2000,因此在此处判断长度
274-
if len(oper_param) > 2000:
275-
oper_param = '请求参数过长'
276-
277-
# 获取操作时间
278-
oper_time = datetime.now()
279-
# 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息
280-
login_log = {}
281-
if log_type == 'login':
282-
user_agent_info = parse(user_agent)
283-
browser = f'{user_agent_info.browser.family}'
284-
system_os = f'{user_agent_info.os.family}'
285-
if user_agent_info.browser.version != ():
286-
browser += f' {user_agent_info.browser.version[0]}'
287-
if user_agent_info.os.version != ():
288-
system_os += f' {user_agent_info.os.version[0]}'
289-
login_log = dict(
290-
ipaddr=oper_ip,
291-
loginLocation=oper_location,
292-
browser=browser,
293-
os=system_os,
294-
loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S'),
295-
)
296-
kwargs['form_data'].login_info = login_log
297-
try:
298-
# 调用原始函数
299-
result = await func(*args, **kwargs)
300-
except (LoginException, ServiceWarning) as e:
301-
logger.warning(e.message)
302-
result = ResponseUtil.failure(data=e.data, msg=e.message)
303-
except ServiceException as e:
304-
logger.error(e.message)
305-
result = ResponseUtil.error(data=e.data, msg=e.message)
306-
except Exception as e:
307-
logger.exception(e)
308-
result = ResponseUtil.error(msg=str(e))
309-
# 获取请求耗时
310-
cost_time = float(time.time() - start_time) * 100
311-
# 判断请求是否来自api文档
312-
request_from_swagger = (
313-
request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
314-
)
315-
request_from_redoc = (
316-
request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
317-
)
318-
# 根据响应结果的类型使用不同的方法获取响应结果参数
319-
if (
320-
isinstance(result, JSONResponse)
321-
or isinstance(result, ORJSONResponse)
322-
or isinstance(result, UJSONResponse)
323-
):
324-
result_dict = json.loads(str(result.body, 'utf-8'))
325-
else:
326-
if request_from_swagger or request_from_redoc:
327-
result_dict = {}
328-
else:
329-
if result.status_code == 200:
330-
result_dict = {'code': result.status_code, 'message': '获取成功'}
331-
else:
332-
result_dict = {'code': result.status_code, 'message': '获取失败'}
333-
json_result = json.dumps(result_dict, ensure_ascii=False)
334-
# 根据响应结果获取响应状态及异常信息
335-
status = 1
336-
error_msg = ''
337-
if result_dict.get('code') == 200:
338-
status = 0
339-
else:
340-
error_msg = result_dict.get('msg')
341-
# 根据日志类型向对应的日志表插入数据
342-
if log_type == 'login':
343-
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
344-
if request_from_swagger or request_from_redoc:
345-
pass
346-
else:
347-
user = kwargs.get('form_data')
348-
user_name = user.username
349-
login_log['loginTime'] = oper_time
350-
login_log['userName'] = user_name
351-
login_log['status'] = str(status)
352-
login_log['msg'] = result_dict.get('msg')
353-
354-
await LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log))
355-
else:
356-
current_user = await LoginService.get_current_user(request, token, query_db)
357-
oper_name = current_user.user.user_name
358-
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
359-
operation_log = OperLogModel(
360-
title=title,
361-
businessType=business_type,
362-
method=func_path,
363-
requestMethod=request_method,
364-
operatorType=operator_type,
365-
operName=oper_name,
366-
deptName=dept_name,
367-
operUrl=oper_url,
368-
operIp=oper_ip,
369-
operLocation=oper_location,
370-
operParam=oper_param,
371-
jsonResult=json_result,
372-
status=status,
373-
errorMsg=error_msg,
374-
operTime=oper_time,
375-
costTime=int(cost_time),
376-
)
377-
await OperationLogService.add_operation_log_services(query_db, operation_log)
378-
379-
return result
380-
381-
return wrapper
382-
383-
return decorator
384-
385-
386203
@lru_cache()
387204
def get_ip_location(oper_ip: str):
388205
"""

ruoyi-fastapi-backend/module_admin/service/job_service.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,7 @@ async def edit_job_services(cls, query_db: AsyncSession, page_object: EditJobMod
129129
raise ServiceException(message=f'修改定时任务{page_object.job_name}失败,定时任务已存在')
130130
try:
131131
await JobDao.edit_job_dao(query_db, edit_job)
132-
query_job = SchedulerUtil.get_scheduler_job(job_id=edit_job.get('job_id'))
133-
if query_job:
134-
SchedulerUtil.remove_scheduler_job(job_id=edit_job.get('job_id'))
132+
SchedulerUtil.remove_scheduler_job(job_id=edit_job.get('job_id'))
135133
if edit_job.get('status') == '0':
136134
job_info = await cls.job_detail_services(query_db, edit_job.get('job_id'))
137135
SchedulerUtil.add_scheduler_job(job_info=job_info)
@@ -152,9 +150,7 @@ async def execute_job_once_services(cls, query_db: AsyncSession, page_object: Jo
152150
:param page_object: 定时任务对象
153151
:return: 执行一次定时任务结果
154152
"""
155-
query_job = SchedulerUtil.get_scheduler_job(job_id=page_object.job_id)
156-
if query_job:
157-
SchedulerUtil.remove_scheduler_job(job_id=page_object.job_id)
153+
SchedulerUtil.remove_scheduler_job(job_id=page_object.job_id)
158154
job_info = await cls.job_detail_services(query_db, page_object.job_id)
159155
if job_info:
160156
SchedulerUtil.execute_scheduler_job_once(job_info=job_info)
@@ -176,9 +172,7 @@ async def delete_job_services(cls, query_db: AsyncSession, page_object: DeleteJo
176172
try:
177173
for job_id in job_id_list:
178174
await JobDao.delete_job_dao(query_db, JobModel(jobId=job_id))
179-
query_job = SchedulerUtil.get_scheduler_job(job_id=job_id)
180-
if query_job:
181-
SchedulerUtil.remove_scheduler_job(job_id=job_id)
175+
SchedulerUtil.remove_scheduler_job(job_id=job_id)
182176
await query_db.commit()
183177
return CrudResponseModel(is_success=True, message='删除成功')
184178
except Exception as e:

ruoyi-fastapi-backend/module_admin/service/menu_service.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,9 @@ async def add_menu_services(cls, query_db: AsyncSession, page_object: MenuModel)
9999
:return: 新增菜单校验结果
100100
"""
101101
if not await cls.check_menu_name_unique_services(query_db, page_object):
102-
raise ServiceException(message=f'新增菜单{page_object.post_name}失败,菜单名称已存在')
102+
raise ServiceException(message=f'新增菜单{page_object.menu_name}失败,菜单名称已存在')
103103
elif page_object.is_frame == MenuConstant.YES_FRAME and not StringUtil.is_http(page_object.path):
104-
raise ServiceException(message=f'新增菜单{page_object.post_name}失败,地址必须以http(s)://开头')
104+
raise ServiceException(message=f'新增菜单{page_object.menu_name}失败,地址必须以http(s)://开头')
105105
else:
106106
try:
107107
await MenuDao.add_menu_dao(query_db, page_object)
@@ -124,11 +124,11 @@ async def edit_menu_services(cls, query_db: AsyncSession, page_object: MenuModel
124124
menu_info = await cls.menu_detail_services(query_db, page_object.menu_id)
125125
if menu_info.menu_id:
126126
if not await cls.check_menu_name_unique_services(query_db, page_object):
127-
raise ServiceException(message=f'修改菜单{page_object.post_name}失败,菜单名称已存在')
127+
raise ServiceException(message=f'修改菜单{page_object.menu_name}失败,菜单名称已存在')
128128
elif page_object.is_frame == MenuConstant.YES_FRAME and not StringUtil.is_http(page_object.path):
129-
raise ServiceException(message=f'修改菜单{page_object.post_name}失败,地址必须以http(s)://开头')
129+
raise ServiceException(message=f'修改菜单{page_object.menu_name}失败,地址必须以http(s)://开头')
130130
elif page_object.menu_id == page_object.parent_id:
131-
raise ServiceException(message=f'修改菜单{page_object.post_name}失败,上级菜单不能选择自己')
131+
raise ServiceException(message=f'修改菜单{page_object.menu_name}失败,上级菜单不能选择自己')
132132
else:
133133
try:
134134
await MenuDao.edit_menu_dao(query_db, edit_menu)

0 commit comments

Comments
 (0)