Skip to content

Commit f3c8187

Browse files
authored
Merge pull request #135 from abravalheri/replace-pickle-in-generated-code
Reconstruct regexes in generated code instead of pickling
2 parents e4b9c46 + f200032 commit f3c8187

File tree

9 files changed

+93835
-3
lines changed

9 files changed

+93835
-3
lines changed

fastjsonschema/generator.py

+19-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from collections import OrderedDict
22
import re
3-
import pickle
43

54
from .exceptions import JsonSchemaValueException, JsonSchemaDefinitionException
65
from .indent import indent
@@ -103,11 +102,11 @@ def global_state_code(self):
103102
'',
104103
])
105104
return '\n'.join(self._extra_imports_lines + [
106-
'import re, pickle',
105+
'import re',
107106
'from fastjsonschema import JsonSchemaValueException',
108107
'',
109108
'',
110-
'REGEX_PATTERNS = pickle.loads(' + str(pickle.dumps(self._compile_regexps)) + ')',
109+
'REGEX_PATTERNS = ' + serialize_regexes(self._compile_regexps),
111110
'',
112111
])
113112

@@ -294,3 +293,20 @@ def create_variable_is_dict(self):
294293
return
295294
self._variables.add(variable_name)
296295
self.l('{variable}_is_dict = isinstance({variable}, dict)')
296+
297+
298+
def serialize_regexes(patterns_dict):
299+
# Unfortunately using `pprint.pformat` is causing errors
300+
# specially with big regexes
301+
regex_patterns = (
302+
repr(k) + ": " + repr_regex(v)
303+
for k, v in patterns_dict.items()
304+
)
305+
return '{\n ' + ",\n ".join(regex_patterns) + "\n}"
306+
307+
308+
def repr_regex(regex):
309+
all_flags = ("A", "I", "DEBUG", "L", "M", "S", "X")
310+
flags = " | ".join(f"re.{f}" for f in all_flags if regex.flags & getattr(re, f))
311+
flags = ", " + flags if flags else ""
312+
return "re.compile({!r}{})".format(regex.pattern, flags)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
data must match pattern ^[ \r\n\t\S]+$
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema#",
3+
"type": "string",
4+
"pattern": "^[ \\r\\n\\t\\S]+$"
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"42"

0 commit comments

Comments
 (0)