Skip to content

Commit 7e1c2c2

Browse files
authored
fix: Unable to parse expression (#4408)
1 parent 0f6cd8a commit 7e1c2c2

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

apps/common/init/init_template.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# coding=utf-8
2+
"""
3+
@project: MaxKB
4+
@Author:虎虎
5+
@file: init_jinja.py
6+
@date:2025/12/1 17:16
7+
@desc:
8+
"""
9+
from typing import Any
10+
11+
from jinja2.sandbox import SandboxedEnvironment
12+
from langchain_core.prompts.string import DEFAULT_FORMATTER_MAPPING, _HAS_JINJA2
13+
14+
15+
def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
16+
"""Format a template using jinja2.
17+
18+
*Security warning*:
19+
As of LangChain 0.0.329, this method uses Jinja2's
20+
SandboxedEnvironment by default. However, this sand-boxing should
21+
be treated as a best-effort approach rather than a guarantee of security.
22+
Do not accept jinja2 templates from untrusted sources as they may lead
23+
to arbitrary Python code execution.
24+
25+
https://jinja.palletsprojects.com/en/3.1.x/sandbox/
26+
27+
Args:
28+
template: The template string.
29+
**kwargs: The variables to format the template with.
30+
31+
Returns:
32+
The formatted string.
33+
34+
Raises:
35+
ImportError: If jinja2 is not installed.
36+
"""
37+
if not _HAS_JINJA2:
38+
msg = (
39+
"jinja2 not installed, which is needed to use the jinja2_formatter. "
40+
"Please install it with `pip install jinja2`."
41+
"Please be cautious when using jinja2 templates. "
42+
"Do not expand jinja2 templates using unverified or user-controlled "
43+
"inputs as that can result in arbitrary Python code execution."
44+
)
45+
raise ImportError(msg)
46+
47+
# Use a restricted sandbox that blocks ALL attribute/method access
48+
# Only simple variable lookups like {{variable}} are allowed
49+
# Attribute access like {{variable.attr}} or {{variable.method()}} is blocked
50+
return SandboxedEnvironment().from_string(template).render(**kwargs)
51+
52+
53+
def run():
54+
DEFAULT_FORMATTER_MAPPING['jinja2'] = jinja2_formatter

apps/maxkb/wsgi/web.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,10 @@ def __call__(self, name, *args, **kwargs):
3939
def post_handler():
4040
from common.database_model_manage.database_model_manage import DatabaseModelManage
4141
from common import event
42-
42+
from common.init import init_template
4343
event.run()
4444
DatabaseModelManage.init()
45+
init_template.run()
4546

4647

4748
# 启动后处理函数

0 commit comments

Comments
 (0)