-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathimage_validators.py
More file actions
197 lines (164 loc) · 5.49 KB
/
image_validators.py
File metadata and controls
197 lines (164 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""Input validators for the image field use in the mock query API."""
import io
import logging
from collections.abc import Mapping
from email.message import EmailMessage
from beartype import beartype
from PIL import Image
from werkzeug.datastructures import FileStorage, MultiDict
from werkzeug.formparser import MultiPartParser
from mock_vws._query_validators.exceptions import (
BadImageError,
ImageNotGivenError,
RequestEntityTooLargeError,
)
_LOGGER = logging.getLogger(name=__name__)
@beartype
def _parse_multipart_files(
*,
request_headers: Mapping[str, str],
request_body: bytes,
) -> MultiDict[str, FileStorage]:
"""Parse the multipart body and return the files section.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Returns:
The files parsed from the multipart body.
"""
email_message = EmailMessage()
email_message["Content-Type"] = request_headers["Content-Type"]
boundary = email_message.get_boundary(failobj="")
parser = MultiPartParser()
_, files = parser.parse(
stream=io.BytesIO(initial_bytes=request_body),
boundary=boundary.encode(encoding="utf-8"),
content_length=len(request_body),
)
return files
@beartype
def validate_image_field_given(
*,
request_headers: Mapping[str, str],
request_body: bytes,
) -> None:
"""Validate that the image field is given.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Raises:
ImageNotGivenError: The image field is not given.
"""
files = _parse_multipart_files(
request_headers=request_headers,
request_body=request_body,
)
if files.get(key="image") is not None:
return
_LOGGER.warning(msg="The image field is not given.")
raise ImageNotGivenError
@beartype
def validate_image_file_size(
*,
request_headers: Mapping[str, str],
request_body: bytes,
) -> None:
"""Validate the file size of the image given to the query endpoint.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Raises:
RequestEntityTooLargeError: The image file size is too large.
"""
files = _parse_multipart_files(
request_headers=request_headers,
request_body=request_body,
)
image_part = files["image"]
image_value = image_part.stream.read()
# This is the documented maximum size of a PNG as per.
# https://developer.vuforia.com/library/web-api/vuforia-query-web-api.
# However, the tests show that this maximum size also applies to JPEG
# files.
max_bytes = 2 * 1024 * 1024
# Ignore coverage on this as there is a bug in urllib3 which means that we
# do not trigger this exception.
# See https://github.com/urllib3/urllib3/issues/2733.
if len(image_value) > max_bytes: # pragma: no cover
_LOGGER.warning(msg="The image file size is too large.")
raise RequestEntityTooLargeError
@beartype
def validate_image_dimensions(
*,
request_headers: Mapping[str, str],
request_body: bytes,
) -> None:
"""Validate the dimensions the image given to the query endpoint.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Raises:
BadImageError: The image is given and is not within the maximum width
and height limits.
"""
files = _parse_multipart_files(
request_headers=request_headers,
request_body=request_body,
)
image_part = files["image"]
image_value = image_part.stream.read()
image_file = io.BytesIO(initial_bytes=image_value)
with Image.open(fp=image_file) as pil_image:
max_width = 30000
max_height = 30000
if pil_image.height <= max_height and pil_image.width <= max_width:
return
_LOGGER.warning(msg="The image dimensions are too large.")
raise BadImageError
@beartype
def validate_image_format(
*,
request_headers: Mapping[str, str],
request_body: bytes,
) -> None:
"""Validate the format of the image given to the query endpoint.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Raises:
BadImageError: The image is given and is not either a PNG or a JPEG.
"""
files = _parse_multipart_files(
request_headers=request_headers,
request_body=request_body,
)
image_part = files["image"]
with Image.open(fp=image_part.stream) as pil_image:
if pil_image.format in {"PNG", "JPEG"}:
return
_LOGGER.warning(msg="The image format is not PNG or JPEG.")
raise BadImageError
@beartype
def validate_image_is_image(
*,
request_headers: Mapping[str, str],
request_body: bytes,
) -> None:
"""Validate that the given image data is actually an image file.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Raises:
BadImageError: Image data is given and it is not an image file.
"""
files = _parse_multipart_files(
request_headers=request_headers,
request_body=request_body,
)
image_file = files["image"].stream
try:
with Image.open(fp=image_file) as _:
pass
except OSError as exc:
_LOGGER.warning(msg="The image is not an image file.")
raise BadImageError from exc