init
This commit is contained in:
@@ -1,21 +1,12 @@
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import traceback
|
||||
from fastapi import Request, status
|
||||
from fastapi.responses import JSONResponse
|
||||
# from fastapi import Request, status
|
||||
|
||||
from api.core.exception import ResponseException
|
||||
|
||||
logFormatter = logging.Formatter(
|
||||
"""
|
||||
[start]
|
||||
%(asctime)s
|
||||
<%(name)s>
|
||||
%(message)s
|
||||
[end]
|
||||
"""
|
||||
)
|
||||
import logging
|
||||
import traceback
|
||||
from fastapi import Request, status
|
||||
from fastapi.responses import JSONResponse
|
||||
# from fastapi import Request, status
|
||||
|
||||
from api.core.exception import ResponseException
|
||||
|
||||
logger = logging.getLogger('dcalc.exception')
|
||||
|
||||
|
||||
def format_exception() -> str:
|
||||
@@ -30,34 +21,12 @@ async def all_exception_handler(request: Request, ex: Exception):
|
||||
info = ''
|
||||
if not isinstance(ex, ResponseException):
|
||||
info = format_exception()
|
||||
if request.client.host != '127.0.0.1':
|
||||
from fastapi.logger import logger
|
||||
logger.setLevel(logging.ERROR)
|
||||
logger.name = 'dcalc'
|
||||
log_directory = 'logs'
|
||||
import os
|
||||
|
||||
if not os.path.exists('./logs'):
|
||||
os.makedirs('./logs')
|
||||
time_str = datetime.now().strftime('%Y_%m_%d')
|
||||
fileHandler = logging.FileHandler(f'{log_directory}/{logger.name}_{time_str}.log', encoding='utf-8')
|
||||
fileHandler.setFormatter(logFormatter)
|
||||
fileHandler.setLevel(logging.ERROR)
|
||||
logger.addHandler(fileHandler)
|
||||
try:
|
||||
import pathlib
|
||||
pathlib.Path(log_directory).mkdir(parents=True, exist_ok=True)
|
||||
except PermissionError:
|
||||
print('创建日志目录logs失败,请确认是否限制了基础的运行权限')
|
||||
logFunc = logger.error
|
||||
try:
|
||||
logFunc(info)
|
||||
info = '服务器内部错误'
|
||||
finally:
|
||||
logger.removeHandler(fileHandler)
|
||||
fileHandler.close()
|
||||
else:
|
||||
info = ex.args[0]
|
||||
client_host = request.client.host if request.client else ''
|
||||
if client_host != '127.0.0.1':
|
||||
logger.error('Unhandled exception for %s', request.url.path, exc_info=(type(ex), ex, ex.__traceback__))
|
||||
info = '服务器内部错误'
|
||||
else:
|
||||
info = ex.args[0]
|
||||
# traceback.print_last(sys.exc_info())
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from config.main import BACKEND_DIR
|
||||
|
||||
|
||||
LOG_DIR = BACKEND_DIR / 'logs'
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
log_path = LOG_DIR / f'dcalc_{datetime.now().strftime("%Y_%m_%d")}.log'
|
||||
|
||||
logger = logging.getLogger('dcalc')
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = True
|
||||
|
||||
if any(isinstance(handler, logging.FileHandler) and Path(handler.baseFilename) == log_path for handler in logger.handlers):
|
||||
return
|
||||
|
||||
handler = logging.FileHandler(log_path, encoding='utf-8')
|
||||
handler.setLevel(logging.ERROR)
|
||||
handler.setFormatter(
|
||||
logging.Formatter(
|
||||
"""
|
||||
[start]
|
||||
%(asctime)s
|
||||
<%(name)s>
|
||||
%(levelname)s
|
||||
%(message)s
|
||||
[end]
|
||||
"""
|
||||
)
|
||||
)
|
||||
logger.addHandler(handler)
|
||||
@@ -8,7 +8,12 @@ import redis
|
||||
|
||||
from api.core.Gzip import gzip_zip
|
||||
from api.utils.skill_detail import SKILL_DETAIL_NORMALIZE_VERSION, normalize_skill_detail
|
||||
from api.utils.openapi_data import logical_skill_detail_prefix
|
||||
from api.utils.openapi_data import (
|
||||
OPENAPI_CUSTOM_CN_PATH,
|
||||
OPENAPI_DATA_DIR,
|
||||
OPENAPI_SKILLS_PATH,
|
||||
logical_skill_detail_prefix,
|
||||
)
|
||||
from api.utils.skill_tree import (
|
||||
SKILL_TREE_NAME_MAP_VERSION,
|
||||
SKILL_TREE_WITH_DESC_SPECIAL_VERSION,
|
||||
@@ -18,7 +23,7 @@ from api.utils.skill_tree import (
|
||||
from core.basic.character import createCharacter
|
||||
from core.basic.equipment import get_equipment
|
||||
from core.character.adventure import adv, get_adv_list
|
||||
from database.connect import BACKEND_DIR, RedisPool
|
||||
from database.connect import RedisPool
|
||||
|
||||
|
||||
PreheatLoader = Callable[[], object]
|
||||
@@ -28,12 +33,12 @@ PREHEAT_LOCK_EXPIRE_SECONDS = 15 * 60
|
||||
|
||||
|
||||
def _load_skills():
|
||||
with (BACKEND_DIR / 'openapi' / 'data' / 'skills.json').open(encoding='utf-8') as file:
|
||||
with OPENAPI_SKILLS_PATH.open(encoding='utf-8') as file:
|
||||
return json.load(file)
|
||||
|
||||
|
||||
def _load_custom_cn():
|
||||
with (BACKEND_DIR / 'openapi' / 'custom_cn.json').open(encoding='utf-8') as file:
|
||||
with OPENAPI_CUSTOM_CN_PATH.open(encoding='utf-8') as file:
|
||||
return json.load(file)
|
||||
|
||||
|
||||
@@ -60,8 +65,7 @@ def _build_character_preheat_tasks(equ_version: str = '0') -> list[PreheatTask]:
|
||||
|
||||
|
||||
def _iter_skill_detail_files() -> list[Path]:
|
||||
data_dir = BACKEND_DIR / 'openapi' / 'data'
|
||||
return sorted(data_dir.glob('cn/*/*/skillDetail/*.json'))
|
||||
return sorted(OPENAPI_DATA_DIR.glob('cn/*/*/skillDetail/*.json'))
|
||||
|
||||
|
||||
def _skill_prefix_from_path(path: Path) -> str:
|
||||
@@ -144,9 +148,8 @@ def _build_skill_data_preheat_tasks(custom_cn: list[dict]) -> list[PreheatTask]:
|
||||
|
||||
def _build_skill_tree_preheat_tasks() -> list[PreheatTask]:
|
||||
tasks: list[PreheatTask] = []
|
||||
data_dir = BACKEND_DIR / 'openapi' / 'data'
|
||||
for path in sorted(data_dir.glob('cn/*/*/skill_tree.json')):
|
||||
relative = path.relative_to(data_dir)
|
||||
for path in sorted(OPENAPI_DATA_DIR.glob('cn/*/*/skill_tree.json')):
|
||||
relative = path.relative_to(OPENAPI_DATA_DIR)
|
||||
job_id = relative.parts[1]
|
||||
job_grow_id = relative.parts[2]
|
||||
tasks.append(
|
||||
|
||||
@@ -10,5 +10,5 @@ register_gzip_request(router)
|
||||
|
||||
|
||||
@router.post('/calc')
|
||||
async def calc(state: AltersDep, config=Body(None)):
|
||||
def calc(state: AltersDep, config=Body(None)):
|
||||
return response(data=calculate(state, config))
|
||||
|
||||
@@ -5,7 +5,7 @@ from api.core.Response import response
|
||||
from api.core.Redis import get_redis_info
|
||||
from api.dp import RedisDep
|
||||
from api.utils.skill_detail import SKILL_DETAIL_NORMALIZE_VERSION, normalize_skill_detail, skill_detail_for_level
|
||||
from api.utils.openapi_data import openapi_locale_path
|
||||
from api.utils.openapi_data import OPENAPI_SKILLS_PATH, OPENAPI_SUMMARY_DIR, openapi_locale_path
|
||||
from api.utils.skill_tree import (
|
||||
SKILL_TREE_WITH_DESC_SPECIAL_VERSION,
|
||||
filter_skill_tree_by_desc_special,
|
||||
@@ -43,7 +43,7 @@ async def get_skills_list(
|
||||
def get_skills():
|
||||
# This function should retrieve the skills list from the data source
|
||||
# For now, we return a placeholder list
|
||||
with open('./openapi/data/skills.json', encoding='utf-8') as f:
|
||||
with OPENAPI_SKILLS_PATH.open(encoding='utf-8') as f:
|
||||
skills_data = json.load(f)
|
||||
return skills_data
|
||||
|
||||
@@ -226,13 +226,12 @@ async def get_skill_data_summary(
|
||||
def get_skill_data_summary():
|
||||
# This function should retrieve the skill data summary based on job
|
||||
# For now, we return a placeholder dictionary
|
||||
summary_dir = './openapi/summary/'
|
||||
json_files = [f for f in os.listdir(summary_dir) if f.endswith('.json')]
|
||||
json_files = [f for f in os.listdir(OPENAPI_SUMMARY_DIR) if f.endswith('.json')]
|
||||
res = []
|
||||
for i in json_files:
|
||||
if job in i:
|
||||
k = re.search(r'^\d+(?:-\d+)?(.*?)_', i)
|
||||
with open(os.path.join(summary_dir, i), encoding='utf-8') as f:
|
||||
with (OPENAPI_SUMMARY_DIR / i).open(encoding='utf-8') as f:
|
||||
skill_data = json.load(f)
|
||||
weapon = i.split('_')[-1].replace('.json', '')
|
||||
res.append({'weapon': weapon if weapon else '通用', 'skills': skill_data, 'job': k.group(1) if k else ''})
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
from pathlib import Path
|
||||
|
||||
from database.connect import BACKEND_DIR
|
||||
from config.main import BACKEND_DIR
|
||||
|
||||
|
||||
OPENAPI_DATA_DIR = BACKEND_DIR / 'openapi' / 'data'
|
||||
OPENAPI_DIR = BACKEND_DIR / 'openapi'
|
||||
OPENAPI_STATIC_DIR = OPENAPI_DIR / 'static'
|
||||
OPENAPI_DATA_DIR = OPENAPI_STATIC_DIR / 'data'
|
||||
OPENAPI_SUMMARY_DIR = OPENAPI_STATIC_DIR / 'summary'
|
||||
OPENAPI_SKILLS_PATH = OPENAPI_DATA_DIR / 'skills.json'
|
||||
OPENAPI_CUSTOM_CN_PATH = OPENAPI_STATIC_DIR / 'custom_cn.json'
|
||||
OPENAPI_RES_DIR = OPENAPI_STATIC_DIR / 'res'
|
||||
LOCALES = {'cn', 'kr'}
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import json
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
from api.utils.openapi_data import openapi_locale_path
|
||||
from database.connect import BACKEND_DIR
|
||||
|
||||
|
||||
SKILL_TREE_WITH_DESC_SPECIAL_VERSION = 'skillTreeWithDescSpecial:v1'
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
try:
|
||||
os.chdir(os.path.dirname(sys.argv[0]))
|
||||
except Exception:
|
||||
pass
|
||||
BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class Config(BaseSettings):
|
||||
DEBUG_MODE: bool = True
|
||||
WORKERS: int = 1
|
||||
PORT:int = 27173
|
||||
PORT: int = 27173
|
||||
MCPPORT: int = 27174
|
||||
REDIS_URL: str = 'redis://localhost:6379/1'
|
||||
COLG_TOKEN: str = ''
|
||||
@@ -19,7 +16,11 @@ class Config(BaseSettings):
|
||||
HELPER_ID: str = ''
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=('config/.env', 'config/.env.dev', 'config/.env.prod'),
|
||||
env_file=(
|
||||
str(BACKEND_DIR / 'config' / '.env'),
|
||||
str(BACKEND_DIR / 'config' / '.env.dev'),
|
||||
str(BACKEND_DIR / 'config' / '.env.prod'),
|
||||
),
|
||||
extra='ignore',
|
||||
)
|
||||
|
||||
|
||||
@@ -9,13 +9,17 @@ core.basic.character 包
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
|
||||
from api.core.exception import ResponseException
|
||||
from .jade import Jade
|
||||
from .calc_equip import CalcEquipMixin
|
||||
from .calc_carry import CalcCarryMixin
|
||||
from .calc_buffer import CalcBufferMixin
|
||||
from .info import CharacterInfoMixin
|
||||
|
||||
logger = logging.getLogger('dcalc.character')
|
||||
|
||||
|
||||
class Character(CalcEquipMixin, CalcCarryMixin, CalcBufferMixin, CharacterInfoMixin):
|
||||
"""
|
||||
@@ -28,15 +32,17 @@ class Character(CalcEquipMixin, CalcCarryMixin, CalcBufferMixin, CharacterInfoMi
|
||||
|
||||
|
||||
def createCharacter(alter: str, equVersion: str = '0') -> 'Character':
|
||||
character: Character = None
|
||||
module_name = 'core.character.' + alter
|
||||
if equVersion is None or equVersion == '':
|
||||
equVersion = '0'
|
||||
try:
|
||||
character = importlib.import_module(module_name).classChange(equVersion)
|
||||
except Exception as ex:
|
||||
print(ex)
|
||||
print('create character ' + module_name + ' error.')
|
||||
logger.exception('create character failed alter=%s equVersion=%s module=%s', alter, equVersion, module_name)
|
||||
raise ResponseException(f'职业加载失败: {alter}') from ex
|
||||
if character is None:
|
||||
logger.error('create character returned None alter=%s equVersion=%s module=%s', alter, equVersion, module_name)
|
||||
raise ResponseException(f'职业加载失败: {alter}')
|
||||
return character
|
||||
|
||||
|
||||
|
||||
@@ -5,15 +5,14 @@ import json
|
||||
import re
|
||||
from typing import Any, Literal, TYPE_CHECKING
|
||||
from .formula import 武器冷却惩罚
|
||||
from database.connect import BACKEND_DIR, get_redis_client
|
||||
from database.connect import get_redis_client
|
||||
from api.core.Redis import get_redis_info
|
||||
from api.utils.openapi_data import logical_skill_detail_path
|
||||
from api.utils.openapi_data import OPENAPI_CUSTOM_CN_PATH, logical_skill_detail_path
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.basic.character import Character
|
||||
|
||||
characterLv = 115 + 5
|
||||
OPENAPI_DIR = BACKEND_DIR / 'openapi'
|
||||
|
||||
|
||||
def _identity(value: Any) -> Any:
|
||||
@@ -22,7 +21,7 @@ def _identity(value: Any) -> Any:
|
||||
|
||||
@cache
|
||||
def _load_custom_cn() -> list[dict[str, Any]]:
|
||||
with (OPENAPI_DIR / 'custom_cn.json').open(encoding='utf-8') as f:
|
||||
with OPENAPI_CUSTOM_CN_PATH.open(encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
import redis
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.pool import NullPool
|
||||
from config.main import config
|
||||
from config.main import BACKEND_DIR, config
|
||||
|
||||
RedisPool = redis.ConnectionPool.from_url(config.REDIS_URL)
|
||||
BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def get_redis_client():
|
||||
|
||||
@@ -7,9 +7,12 @@ import uvicorn
|
||||
from fastapi import FastAPI
|
||||
|
||||
from api.core import Exceptions, Gzip, Middleware
|
||||
from api.core.Logging import configure_logging
|
||||
from api.main import api_router
|
||||
from config.main import config
|
||||
|
||||
configure_logging()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
|
||||
+1
-1
Submodule backend/openapi updated: 27e2652dd0...e82703643a
Reference in New Issue
Block a user