1from .draft06 import CodeGeneratorDraft06
2
3
4class CodeGeneratorDraft07(CodeGeneratorDraft06):
5 FORMAT_REGEXS = dict(CodeGeneratorDraft06.FORMAT_REGEXS, **{
6 'date': r'^(?P<year>\d{4})-(?P<month>(0[1-9]|1[0-2]))-(?P<day>(0[1-9]|[12]\d|3[01]))\Z',
7 'iri': r'^\w+:(\/?\/?)[^\s]+\Z',
8 'iri-reference': r'^(\w+:(\/?\/?))?[^#\\\s]*(#[^\\\s]*)?\Z',
9 'idn-email': r'^[^@]+@[^@]+\.[^@]+\Z',
10 # pylint: disable=line-too-long
11 'idn-hostname': r'^(?!-)(xn--)?[a-zA-Z0-9][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.(?!-)(xn--)?([a-zA-Z0-9\-]{1,50}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,})$',
12 'relative-json-pointer': r'^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)\Z',
13 #'regex': r'',
14 'time': (
15 r'^(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
16 r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6}))?'
17 r'([zZ]|[+-]\d\d:\d\d)?)?\Z'
18 ),
19 })
20
21 def __init__(
22 self,
23 definition,
24 resolver=None,
25 formats={},
26 use_default=True,
27 use_formats=True,
28 detailed_exceptions=True,
29 fast_fail=True
30 ):
31 super().__init__(definition, resolver, formats, use_default, use_formats, detailed_exceptions, fast_fail)
32 # pylint: disable=duplicate-code
33 self._json_keywords_to_function.update((
34 ('if', self.generate_if_then_else),
35 ('contentEncoding', self.generate_content_encoding),
36 ('contentMediaType', self.generate_content_media_type),
37 ))
38
39 def generate_if_then_else(self):
40 """
41 Implementation of if-then-else.
42
43 .. code-block:: python
44
45 {
46 'if': {
47 'exclusiveMaximum': 0,
48 },
49 'then': {
50 'minimum': -10,
51 },
52 'else': {
53 'multipleOf': 2,
54 },
55 }
56
57 Valid values are any between -10 and 0 or any multiplication of two.
58 """
59 with self.l('try:', optimize=False):
60 self.generate_func_code_block(
61 self._definition['if'],
62 self._variable,
63 self._variable_name,
64 clear_variables=True
65 )
66 with self.l('except JsonSchemaValueException:'):
67 if 'else' in self._definition:
68 self.generate_func_code_block(
69 self._definition['else'],
70 self._variable,
71 self._variable_name,
72 clear_variables=True
73 )
74 else:
75 self.l('pass')
76 if 'then' in self._definition:
77 with self.l('else:'):
78 self.generate_func_code_block(
79 self._definition['then'],
80 self._variable,
81 self._variable_name,
82 clear_variables=True
83 )
84
85 def generate_content_encoding(self):
86 """
87 Means decoding value when it's encoded by base64.
88
89 .. code-block:: python
90
91 {
92 'contentEncoding': 'base64',
93 }
94 """
95 if self._definition['contentEncoding'] == 'base64':
96 with self.l('if isinstance({variable}, str):'):
97 with self.l('try:'):
98 self.l('import base64')
99 self.l('{variable} = base64.b64decode({variable})')
100 with self.l('except Exception:'):
101 self.exc('{name} must be encoded by base64')
102 with self.l('if {variable} == "":'):
103 self.exc('contentEncoding must be base64')
104
105 def generate_content_media_type(self):
106 """
107 Means loading value when it's specified as JSON.
108
109 .. code-block:: python
110
111 {
112 'contentMediaType': 'application/json',
113 }
114 """
115 if self._definition['contentMediaType'] == 'application/json':
116 with self.l('if isinstance({variable}, bytes):'):
117 with self.l('try:'):
118 self.l('{variable} = {variable}.decode("utf-8")')
119 with self.l('except Exception:'):
120 self.exc('{name} must encoded by utf8')
121 with self.l('if isinstance({variable}, str):'):
122 with self.l('try:'):
123 self.l('import json')
124 self.l('{variable} = json.loads({variable})')
125 with self.l('except Exception:'):
126 self.exc('{name} must be valid JSON')