Skip to content

Commit

Permalink
feat: add some comment, add jinja2 for replacing variables
Browse files Browse the repository at this point in the history
  • Loading branch information
wuranxu committed Jan 18, 2024
1 parent bdb03e7 commit 56e1293
Show file tree
Hide file tree
Showing 4 changed files with 190 additions and 1 deletion.
110 changes: 110 additions & 0 deletions app/core/functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import random
import uuid as uid
from datetime import datetime, timedelta

FMT = "%Y-%m-%d %H:%M:%S"
FMT_S = "%Y-%m-%d %H:%M:%S.%f+0000"


class PityFunction(object):

@staticmethod
def now(mode: int = 1):
"""
获取当前时间 默认参数为1
eg: now(2)
:param mode: 模式
1为当前时间戳,如 2023-09-15 11:00:00
2为当前时间戳
3为当前时间戳(毫秒级别)
:return:
"""
if mode == 1:
return datetime.now().strftime(FMT)
if mode == 2:
return int(datetime.now().timestamp())
if mode == 3:
return int(datetime.now().timestamp()) * 1000

@staticmethod
def uuid():
"""
获取当前uuid,常用于RequestId
eg: uuid()
:return:
"""
return str(uid.uuid4()).replace("-", "")

@staticmethod
def sec_before(s: int):
"""
获取N秒之前的时间戳
eg: sec_before(30)
:param s: 秒数
:return:
"""
return int(datetime.now().timestamp()) - s

@staticmethod
def hour_before(h: int):
"""
获取N小时之前的时间戳
eg: hour_before(6)
:param h: 小时数
:return:
"""
return int(datetime.now().timestamp()) - 60 * 60 * h

@staticmethod
def day_before(d: int):
"""
获取N天之前的时间戳
eg: day_before(1)
:param d: 天数
:return:
"""
return int(datetime.now().timestamp()) - 60 * 60 * 24 * d

@staticmethod
def get_unit(unit: str):
if unit == "d":
return "days"
if unit == "h":
return "hours"
if unit == "s":
return "seconds"

@staticmethod
def time_before(unit: str, num: int):
"""
获取当前时间之前时间
eg: time_before("d", 3) 获取3天前的时间戳
:param unit: 单位,支持"d", "h", "s" 分别为天、小时、秒
:param num: 数量
:return:
"""
ut = PityFunction.get_unit(unit)
return datetime.now() - timedelta(**{ut: num})

@staticmethod
def time_after(unit: str, num: int):
"""
获取当前时间之后时间
eg: time_after("h", 3)
:param unit: 单位,支持"d", "h", "s" 分别为天、小时、秒
:param num: 数量
:return:
"""
ut = PityFunction.get_unit(unit)
return datetime.now() + timedelta(**{ut: num})

@staticmethod
def random_int(a, b):
"""
返回a~b之间的随机数
eg: random_int(0, 30)
:param a: 开始
:param b: 结束
:return:
"""
return random.randint(a, b)
76 changes: 76 additions & 0 deletions app/core/render.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""
通过jinja2模板引擎解析上下文
"""
from functools import lru_cache

from jinja2 import Environment

from app.core.functions import PityFunction


def get_env():
my_env = Environment()
for func in dir(PityFunction):
if func.startswith("__"):
continue
my_env.globals[func] = getattr(PityFunction, func)
return my_env


class Render(object):
"""
渲染变量,用于上下文变量替换
"""
_env = get_env()

@staticmethod
@lru_cache(128)
def load(source: str):
"""
加载模板
:param source:
:return:
"""
return Render._env.from_string(source)

@staticmethod
def render(context: dict, source: str):
"""
加载变量
:param context:
:param source:
:return:
"""
try:
tmpl = Render.load(source)
return tmpl.render(**context)
except Exception as e:
raise Exception(f"解析参数失败, 请检查变量是否获取到: {str(e)}")


if __name__ == "__main__":
# import jinja2
#
# template = jinja2.Template("""hello {{nan.xixi[0].orderId}} """)
#
# from jinja2 import Environment
# from jinja2.runtime import Context
#
# env = Environment()

a = "2023-09-14 12:00:00.223"
temp = """{{uuid()}}"""

c = Render.render(dict(), temp)
print(c)

js_dat = {
"nan": {
"xixi": [
{
"ni_zai_gan_ma": "hahahaha",
"orderId": 44
}
]
}
}
3 changes: 3 additions & 0 deletions app/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@


def create_database():
"""
当db不存在时,自动创建db
"""
engine = create_engine('mysql+mysqlconnector://{}:{}@{}:{}'.format(
Config.MYSQL_USER, Config.MYSQL_PWD, Config.MYSQL_HOST, Config.MYSQL_PORT), echo=True)
with engine.connect() as conn:
Expand Down
2 changes: 1 addition & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class Config:


# 获取pity环境变量
PITY_ENV = os.environ.get("pity_env", "pro")
PITY_ENV = os.environ.get("pity_env", "dev")
# 如果pity_env存在且为prod
Config = ProConfig() if PITY_ENV and PITY_ENV.lower() == "pro" else DevConfig()

Expand Down

0 comments on commit 56e1293

Please sign in to comment.