Skip to content

Commit 2bade4d

Browse files
insistencegitee-org
authored andcommitted
!7 RuoYi-Vue3-FastAPI v1.1.0
Merge pull request !7 from insistence/develop
2 parents 303612e + a06c9f1 commit 2bade4d

File tree

13 files changed

+160
-133
lines changed

13 files changed

+160
-133
lines changed

README.md

Lines changed: 4 additions & 3 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-Vue3-FastAPI v1.0.3</h1>
4+
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">RuoYi-Vue3-FastAPI v1.1.0</h1>
55
<h4 align="center">基于RuoYi-Vue3+FastAPI前后端分离的快速开发框架</h4>
66
<p align="center">
77
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI/stargazers"><img src="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI/badge/star.svg?theme=dark"></a>
88
<a href="https://github.com/insistence/RuoYi-Vue3-FastAPI"><img src="https://img.shields.io/github/stars/insistence/RuoYi-Vue3-FastAPI?style=social"></a>
9-
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI"><img src="https://img.shields.io/badge/RuoYiVue3FastAPI-v1.0.3-brightgreen.svg"></a>
9+
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI"><img src="https://img.shields.io/badge/RuoYiVue3FastAPI-v1.1.0-brightgreen.svg"></a>
1010
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-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.8-blue">
1212
<img src="https://img.shields.io/badge/MySQL-≥5.7-blue">
@@ -15,9 +15,10 @@
1515

1616

1717

18+
1819
## 平台简介
1920

20-
RuoYi-Vue-FastAPI是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
21+
RuoYi-Vue3-FastAPI是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
2122

2223
* 前端采用Vue、Element Plus,基于<u>[RuoYi-Vue3](https://github.com/yangzongzhuan/RuoYi-Vue3)</u>前端项目修改。
2324
* 后端采用FastAPI、sqlalchemy、MySQL、Redis、OAuth2 & Jwt。

ruoyi-fastapi-backend/.env.dev

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,13 @@ APP_HOST = '0.0.0.0'
1010
# 应用端口
1111
APP_PORT = 9099
1212
# 应用版本
13-
APP_VERSION= '1.0.3'
13+
APP_VERSION= '1.1.0'
1414
# 应用是否开启热重载
1515
APP_RELOAD = true
16+
# 应用是否开启IP归属区域查询
17+
APP_IP_LOCATION_QUERY = true
18+
# 应用是否允许账号同时登录
19+
APP_SAME_TIME_LOGIN = true
1620

1721
# -------- Jwt配置 --------
1822
# Jwt秘钥
@@ -36,6 +40,8 @@ DB_USERNAME = 'root'
3640
DB_PASSWORD = 'mysqlroot'
3741
# 数据库名称
3842
DB_DATABASE = 'ruoyi-fastapi'
43+
# 是否开启sqlalchemy日志
44+
DB_ECHO = true
3945

4046
# -------- Redis配置 --------
4147
# Redis主机

ruoyi-fastapi-backend/.env.prod

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,13 @@ APP_HOST = '0.0.0.0'
1010
# 应用端口
1111
APP_PORT = 9099
1212
# 应用版本
13-
APP_VERSION= '1.0.3'
13+
APP_VERSION= '1.1.0'
1414
# 应用是否开启热重载
1515
APP_RELOAD = false
16+
# 应用是否开启IP归属区域查询
17+
APP_IP_LOCATION_QUERY = true
18+
# 应用是否允许账号同时登录
19+
APP_SAMETIME_LOGIN = true
1620

1721
# -------- Jwt配置 --------
1822
# Jwt秘钥
@@ -36,6 +40,8 @@ DB_USERNAME = 'root'
3640
DB_PASSWORD = 'root'
3741
# 数据库名称
3842
DB_DATABASE = 'ruoyi-fastapi'
43+
# 是否开启sqlalchemy日志
44+
DB_ECHO = true
3945

4046
# -------- Redis配置 --------
4147
# Redis主机

ruoyi-fastapi-backend/config/database.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
f"{DataBaseConfig.db_host}:{DataBaseConfig.db_port}/{DataBaseConfig.db_database}"
99

1010
engine = create_engine(
11-
SQLALCHEMY_DATABASE_URL, echo=True
11+
SQLALCHEMY_DATABASE_URL, echo=DataBaseConfig.db_echo
1212
)
1313
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
1414
Base = declarative_base()

ruoyi-fastapi-backend/config/env.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ class AppSettings(BaseSettings):
1717
app_port: int = 9099
1818
app_version: str = '1.0.0'
1919
app_reload: bool = True
20+
app_ip_location_query: bool = True
21+
app_same_time_login: bool = True
2022

2123

2224
class JwtSettings(BaseSettings):
@@ -38,6 +40,7 @@ class DataBaseSettings(BaseSettings):
3840
db_username: str = 'root'
3941
db_password: str = 'mysqlroot'
4042
db_database: str = 'ruoyi-fastapi'
43+
db_echo: bool = True
4144

4245

4346
class RedisSettings(BaseSettings):

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

Lines changed: 113 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from module_admin.service.login_service import LoginService
1313
from module_admin.service.log_service import OperationLogService, LoginLogService
1414
from module_admin.entity.vo.log_vo import OperLogModel, LogininforModel
15+
from config.env import AppConfig
1516

1617

1718
def log_decorator(title: str, business_type: int, log_type: Optional[str] = 'operation'):
@@ -50,122 +51,126 @@ async def wrapper(*args, **kwargs):
5051
# 获取请求的ip及ip归属区域
5152
oper_ip = request.headers.get("X-Forwarded-For")
5253
oper_location = '内网IP'
53-
try:
54-
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
55-
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
56-
if ip_result.status_code == 200:
57-
prov = ip_result.json().get('data').get('prov')
58-
city = ip_result.json().get('data').get('city')
59-
if prov or city:
60-
oper_location = f'{prov}-{city}'
54+
if AppConfig.app_ip_location_query:
55+
try:
56+
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
57+
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
58+
if ip_result.status_code == 200:
59+
prov = ip_result.json().get('data').get('prov')
60+
city = ip_result.json().get('data').get('city')
61+
if prov or city:
62+
oper_location = f'{prov}-{city}'
63+
else:
64+
oper_location = '未知'
6165
else:
6266
oper_location = '未知'
63-
else:
64-
oper_location = '未知'
65-
except Exception as e:
66-
oper_location = '未知'
67-
print(e)
68-
finally:
69-
# 根据不同的请求类型使用不同的方法获取请求参数
70-
content_type = request.headers.get("Content-Type")
71-
if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type):
72-
payload = await request.form()
73-
oper_param = "\n".join([f"{key}: {value}" for key, value in payload.items()])
74-
else:
75-
payload = await request.body()
76-
# 通过 request.path_params 直接访问路径参数
77-
path_params = request.path_params
78-
oper_param = {}
79-
if payload:
80-
oper_param.update(json.loads(str(payload, 'utf-8')))
81-
if path_params:
82-
oper_param.update(path_params)
83-
oper_param = json.dumps(oper_param, ensure_ascii=False)
84-
# 日志表请求参数字段长度最大为2000,因此在此处判断长度
85-
if len(oper_param) > 2000:
86-
oper_param = '请求参数过长'
67+
except Exception as e:
68+
oper_location = '未知'
69+
print(e)
70+
# 根据不同的请求类型使用不同的方法获取请求参数
71+
content_type = request.headers.get("Content-Type")
72+
if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type):
73+
payload = await request.form()
74+
oper_param = "\n".join([f"{key}: {value}" for key, value in payload.items()])
75+
else:
76+
payload = await request.body()
77+
# 通过 request.path_params 直接访问路径参数
78+
path_params = request.path_params
79+
oper_param = {}
80+
if payload:
81+
oper_param.update(json.loads(str(payload, 'utf-8')))
82+
if path_params:
83+
oper_param.update(path_params)
84+
oper_param = json.dumps(oper_param, ensure_ascii=False)
85+
# 日志表请求参数字段长度最大为2000,因此在此处判断长度
86+
if len(oper_param) > 2000:
87+
oper_param = '请求参数过长'
8788

88-
# 获取操作时间
89-
oper_time = datetime.now()
90-
# 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息
91-
login_log = {}
92-
if log_type == 'login':
93-
user_agent_info = parse(user_agent)
94-
browser = f'{user_agent_info.browser.family} {user_agent_info.browser.version[0]}'
95-
system_os = f'{user_agent_info.os.family} {user_agent_info.os.version[0]}'
96-
login_log = dict(
97-
ipaddr=oper_ip,
98-
loginLocation=oper_location,
99-
browser=browser,
100-
os=system_os,
101-
loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S')
102-
)
103-
kwargs['form_data'].login_info = login_log
104-
# 调用原始函数
105-
result = await func(*args, **kwargs)
106-
# 获取请求耗时
107-
cost_time = float(time.time() - start_time) * 100
108-
# 判断请求是否来自api文档
109-
request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
110-
request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
111-
# 根据响应结果的类型使用不同的方法获取响应结果参数
112-
if isinstance(result, JSONResponse) or isinstance(result, ORJSONResponse) or isinstance(result, UJSONResponse):
113-
result_dict = json.loads(str(result.body, 'utf-8'))
89+
# 获取操作时间
90+
oper_time = datetime.now()
91+
# 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息
92+
login_log = {}
93+
if log_type == 'login':
94+
user_agent_info = parse(user_agent)
95+
browser = f'{user_agent_info.browser.family}'
96+
system_os = f'{user_agent_info.os.family}'
97+
if user_agent_info.browser.version != ():
98+
browser += f' {user_agent_info.browser.version[0]}'
99+
if user_agent_info.os.version != ():
100+
system_os += f' {user_agent_info.os.version[0]}'
101+
login_log = dict(
102+
ipaddr=oper_ip,
103+
loginLocation=oper_location,
104+
browser=browser,
105+
os=system_os,
106+
loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S')
107+
)
108+
kwargs['form_data'].login_info = login_log
109+
# 调用原始函数
110+
result = await func(*args, **kwargs)
111+
# 获取请求耗时
112+
cost_time = float(time.time() - start_time) * 100
113+
# 判断请求是否来自api文档
114+
request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
115+
request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
116+
# 根据响应结果的类型使用不同的方法获取响应结果参数
117+
if isinstance(result, JSONResponse) or isinstance(result, ORJSONResponse) or isinstance(result, UJSONResponse):
118+
result_dict = json.loads(str(result.body, 'utf-8'))
119+
else:
120+
if request_from_swagger or request_from_redoc:
121+
result_dict = {}
114122
else:
115-
if request_from_swagger or request_from_redoc:
116-
result_dict = {}
123+
if result.status_code == 200:
124+
result_dict = {'code': result.status_code, 'message': '获取成功'}
117125
else:
118-
if result.status_code == 200:
119-
result_dict = {'code': result.status_code, 'message': '获取成功'}
120-
else:
121-
result_dict = {'code': result.status_code, 'message': '获取失败'}
122-
json_result = json.dumps(result_dict, ensure_ascii=False)
123-
# 根据响应结果获取响应状态及异常信息
124-
status = 1
125-
error_msg = ''
126-
if result_dict.get('code') == 200:
127-
status = 0
126+
result_dict = {'code': result.status_code, 'message': '获取失败'}
127+
json_result = json.dumps(result_dict, ensure_ascii=False)
128+
# 根据响应结果获取响应状态及异常信息
129+
status = 1
130+
error_msg = ''
131+
if result_dict.get('code') == 200:
132+
status = 0
133+
else:
134+
error_msg = result_dict.get('msg')
135+
# 根据日志类型向对应的日志表插入数据
136+
if log_type == 'login':
137+
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
138+
if request_from_swagger or request_from_redoc:
139+
pass
128140
else:
129-
error_msg = result_dict.get('msg')
130-
# 根据日志类型向对应的日志表插入数据
131-
if log_type == 'login':
132-
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
133-
if request_from_swagger or request_from_redoc:
134-
pass
135-
else:
136-
user = kwargs.get('form_data')
137-
user_name = user.username
138-
login_log['loginTime'] = oper_time
139-
login_log['userName'] = user_name
140-
login_log['status'] = str(status)
141-
login_log['msg'] = result_dict.get('msg')
141+
user = kwargs.get('form_data')
142+
user_name = user.username
143+
login_log['loginTime'] = oper_time
144+
login_log['userName'] = user_name
145+
login_log['status'] = str(status)
146+
login_log['msg'] = result_dict.get('msg')
142147

143-
LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log))
144-
else:
145-
current_user = await LoginService.get_current_user(request, token, query_db)
146-
oper_name = current_user.user.user_name
147-
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
148-
operation_log = OperLogModel(
149-
title=title,
150-
businessType=business_type,
151-
method=func_path,
152-
requestMethod=request_method,
153-
operatorType=operator_type,
154-
operName=oper_name,
155-
deptName=dept_name,
156-
operUrl=oper_url,
157-
operIp=oper_ip,
158-
operLocation=oper_location,
159-
operParam=oper_param,
160-
jsonResult=json_result,
161-
status=status,
162-
errorMsg=error_msg,
163-
operTime=oper_time,
164-
costTime=int(cost_time)
165-
)
166-
OperationLogService.add_operation_log_services(query_db, operation_log)
148+
LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log))
149+
else:
150+
current_user = await LoginService.get_current_user(request, token, query_db)
151+
oper_name = current_user.user.user_name
152+
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
153+
operation_log = OperLogModel(
154+
title=title,
155+
businessType=business_type,
156+
method=func_path,
157+
requestMethod=request_method,
158+
operatorType=operator_type,
159+
operName=oper_name,
160+
deptName=dept_name,
161+
operUrl=oper_url,
162+
operIp=oper_ip,
163+
operLocation=oper_location,
164+
operParam=oper_param,
165+
jsonResult=json_result,
166+
status=status,
167+
errorMsg=error_msg,
168+
operTime=oper_time,
169+
costTime=int(cost_time)
170+
)
171+
OperationLogService.add_operation_log_services(query_db, operation_log)
167172

168-
return result
173+
return result
169174

170175
return wrapper
171176

ruoyi-fastapi-backend/module_admin/controller/login_controller.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,13 @@ async def login(request: Request, form_data: CustomOAuth2PasswordRequestForm = D
4141
},
4242
expires_delta=access_token_expires
4343
)
44-
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}", access_token,
45-
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
46-
# 此方法可实现同一账号同一时间只能登录一次
47-
# await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{result[0].user_id}", access_token,
48-
# ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
44+
if AppConfig.app_same_time_login:
45+
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}", access_token,
46+
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
47+
else:
48+
# 此方法可实现同一账号同一时间只能登录一次
49+
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{result[0].user_id}", access_token,
50+
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
4951
UserService.edit_user_services(query_db, EditUserModel(userId=result[0].user_id, loginDate=datetime.now(), type='status'))
5052
logger.info('登录成功')
5153
# 判断请求是否来自于api文档,如果是返回指定格式的结果,用于修复api文档认证成功后token显示undefined的bug
@@ -131,7 +133,7 @@ async def register_user(request: Request, user_register: UserRegister, query_db:
131133
@loginController.post("/logout")
132134
async def logout(request: Request, token: Optional[str] = Depends(oauth2_scheme)):
133135
try:
134-
payload = jwt.decode(token, JwtConfig.jwt_secret_key, algorithms=[JwtConfig.jwt_algorithm])
136+
payload = jwt.decode(token, JwtConfig.jwt_secret_key, algorithms=[JwtConfig.jwt_algorithm], options={'verify_exp': False})
135137
session_id: str = payload.get("session_id")
136138
await LoginService.logout_services(request, session_id)
137139
logger.info('退出成功')

0 commit comments

Comments
 (0)