Skip to content

Commit

Permalink
feat: 请求速率限制逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
helloplhm-qwq committed Nov 26, 2023
1 parent 240b443 commit 208199a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ class ConfigReadException(Exception):
"_proxy-desc": "代理配置,HTTP与HTTPS协议需分开配置",
},
"security": {
"rate_limit": {
"global": 0,
"ip": 0,
"desc": "请求速率限制,global为全局,ip为单个ip,填入的值为至少间隔多久才能进行一次请求,单位:秒,不限制请填为0"
}
"key": {
"enable": False,
"_enable-desc": "是否开启请求key,开启后只有请求头中包含key,且值一样时可以访问API",
Expand Down
15 changes: 15 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from common import Httpx
from apis import SongURL
import traceback
import time
Httpx.checkcn()

@app.route('/')
Expand Down Expand Up @@ -75,7 +76,21 @@ def check():
# check ip
if (config.check_ip_banned(request.remote_addr)):
return utils.format_dict_json({"code": 1, "msg": "您的IP已被封禁", "data": None}), 403
# check global rate limit
if (
(config.getRequestTime('global') - time.time())

This comment has been minimized.

Copy link
@DustScribe

DustScribe Nov 27, 2023

Contributor

项目首次运行的时候,config.getRequestTime('global') - time.time()值小于0,会导致所有请求 429。需要过滤没设置初始值的情况

<
(config.read_config("security.rate_limit.global"))
):
return utils.format_dict_json({"code": 5, "msg": "全局限速", "data": None}), 429
if (
(config.getRequestTime(request.remote_addr) - time.time())
<
(config.read_config("security.rate_limit.ip"))
):
return utils.format_dict_json({"code": 5, "msg": "IP限速", "data": None}), 429
# update request time
config.updateRequestTime('global')
config.updateRequestTime(request.remote_addr)
# check host
if (config.read_config("security.allowed_host.enable")):
Expand Down

0 comments on commit 208199a

Please sign in to comment.