Skip to content

Commit

Permalink
revert: fix: flask
Browse files Browse the repository at this point in the history
  • Loading branch information
helloplhm-qwq committed Dec 15, 2023
1 parent 7f852e0 commit dfaed5c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 24 deletions.
4 changes: 0 additions & 4 deletions common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import xmltodict
from urllib.parse import quote
from hashlib import md5 as handleCreateMD5
from aiohttp.web import Response
# from flask import Response

def createBase64Encode(data_bytes):
Expand Down Expand Up @@ -90,9 +89,6 @@ def unique_list(list_in):
[unique_list.append(x) for x in list_in if x not in unique_list]
return unique_list

def handleResult(dic, status = 200):
return Response(body = json.dumps(dic, indent=2, ensure_ascii=False), content_type='application/json', status = status)

def encodeURIComponent(component):
return quote(component)

Expand Down
9 changes: 5 additions & 4 deletions main-flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,21 @@
from common import log

flask_logger = log.log('flask')
logging.getLogger('werkzeug').addHandler(log.flaskLogHelper(flask_logger))
logging.getLogger('werkzeug').addHandler(log.LogHelper(flask_logger))
logger = log.log("main")

from common import utils
from common import lxsecurity
from common import Httpx
from modules import SongURL
from modules import handleApiRequest
from flask import Response
import ujson as json
import traceback
import time
Httpx.checkcn()

def handleResult(dic):
return Response(body = json.dumps(dic, indent=2, ensure_ascii=False), mimetype='application/json')
return Response(json.dumps(dic, indent=2, ensure_ascii=False), mimetype='application/json')

@app.route('/')
def index():
Expand All @@ -57,7 +58,7 @@ async def handle(method, source, songId, quality):

if method == 'url':
try:
return handleResult(await SongURL(source, songId, quality))
return handleResult(await handleApiRequest(source, songId, quality))
except Exception as e:
logger.error(traceback.format_exc())
return handleResult({'code': 4, 'msg': '内部服务器错误', 'data': None}), 500
Expand Down
34 changes: 18 additions & 16 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,14 @@
from common import log
from common import Httpx
from modules import handleApiRequest
from aiohttp.web import Response
import ujson as json
import traceback
import time

def handleResult(dic, status = 200):
return Response(body = json.dumps(dic, indent=2, ensure_ascii=False), content_type='application/json', status = status)

logger = log.log("main")
aiologger = log.log('aiohttp_web')

Expand All @@ -32,20 +37,20 @@ async def handle_request(request):
request.remote = request.headers.get("X-Real-IP")
# check ip
if (config.check_ip_banned(request.remote)):
return utils.handleResult({"code": 1, "msg": "您的IP已被封禁", "data": None}, 403)
return handleResult({"code": 1, "msg": "您的IP已被封禁", "data": None}, 403)
# check global rate limit
if (
(time.time() - config.getRequestTime('global'))
<
(config.read_config("security.rate_limit.global"))
):
return utils.handleResult({"code": 5, "msg": "全局限速", "data": None}, 429)
return handleResult({"code": 5, "msg": "全局限速", "data": None}, 429)
if (
(time.time() - config.getRequestTime(request.remote))
<
(config.read_config("security.rate_limit.ip"))
):
return utils.handleResult({"code": 5, "msg": "IP限速", "data": None}, 429)
return handleResult({"code": 5, "msg": "IP限速", "data": None}, 429)
# update request time
config.updateRequestTime('global')
config.updateRequestTime(request.remote)
Expand All @@ -54,21 +59,18 @@ async def handle_request(request):
if request.remote_host.split(":")[0] not in config.read_config("security.allowed_host.list"):
if config.read_config("security.allowed_host.blacklist.enable"):
config.ban_ip(request.remote, int(config.read_config("security.allowed_host.blacklist.length")))
return utils.handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
return handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
try:
resp = await handler(request)
aiologger.info(f'{request.remote} - {request.method} "{request.path}", {resp.status}')
return resp
except web.HTTPException as ex:
if ex.status == 500: # 捕获500错误
return utils.handleResult({"code": 4, "msg": "内部服务器错误", "data": None}, 500)
else:
logger.error(traceback.format_exc())
return utils.handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
except:
logger.error(traceback.format_exc())
return {"code": 4, "msg": "内部服务器错误", "data": None}
return handle_request

async def main(request):
return utils.handleResult({"code": 0, "msg": "success", "data": None})
return handleResult({"code": 0, "msg": "success", "data": None})


async def handle(request):
Expand All @@ -80,22 +82,22 @@ async def handle(request):
if (request.headers.get("X-Request-Key")) != config.read_config("security.key.value"):
if (config.read_config("security.key.ban")):
config.ban_ip(request.remote)
return utils.handleResult({"code": 1, "msg": "key验证失败", "data": None}, 403)
return handleResult({"code": 1, "msg": "key验证失败", "data": None}, 403)
if (config.read_config('security.check_lxm.enable') and request.host.split(':')[0] not in config.read_config('security.whitelist_host')):
lxm = request.headers.get('lxm')
if (not lxsecurity.checklxmheader(lxm, request.url)):
if (config.read_config('security.lxm_ban.enable')):
config.ban_ip(request.remote)
return utils.handleResult({"code": 1, "msg": "lxm请求头验证失败", "data": None}, 403)
return handleResult({"code": 1, "msg": "lxm请求头验证失败", "data": None}, 403)

try:
return utils.handleResult(await handleApiRequest(method, source, songId, quality))
return handleResult(await handleApiRequest(method, source, songId, quality))
except Exception as e:
logger.error(traceback.format_exc())
return utils.handleResult({'code': 4, 'msg': '内部服务器错误', 'data': None}, 500)
return handleResult({'code': 4, 'msg': '内部服务器错误', 'data': None}, 500)

async def handle_404(request):
return utils.handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
return handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)

app = web.Application(middlewares=[handle_before_request])
# mainpage
Expand Down

0 comments on commit dfaed5c

Please # to comment.