Skip to content

Commit 6744a2d

Browse files
authored
Add bytearray type to make a difference between filename and image bytes in Python 2 (#45)
1 parent 7c6a06d commit 6744a2d

4 files changed

Lines changed: 49 additions & 22 deletions

File tree

aspose_barcode_cloud/api_client.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ class ApiClient(object):
6969
to the API
7070
"""
7171

72-
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
72+
PRIMITIVE_TYPES = (float, bool, bytes, bytearray, six.text_type) + six.integer_types
7373
NATIVE_TYPES_MAPPING = {
7474
"int": int,
7575
"long": int if six.PY3 else long, # noqa: F821
@@ -207,7 +207,7 @@ def __call_api(
207207
if _return_http_data_only:
208208
return return_data
209209
else:
210-
return (return_data, response_data.status, response_data.getheaders())
210+
return return_data, response_data.status, response_data.getheaders()
211211

212212
def sanitize_for_serialization(self, obj):
213213
"""Builds a JSON POST object.
@@ -285,7 +285,7 @@ def __deserialize(self, data, klass):
285285

286286
if type(klass) == str:
287287
if klass.startswith("list["):
288-
sub_kls = re.match(r"list\[(.*)\]", klass).group(1)
288+
sub_kls = re.match(r"list\[(.*)]", klass).group(1)
289289
return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
290290

291291
if klass.startswith("dict("):
@@ -338,13 +338,13 @@ def call_api(
338338
:param header_params: Header parameters to be
339339
placed in the request header.
340340
:param body: Request body.
341-
:param post_params dict: Request post form parameters,
341+
:param post_params: dict: Request post form parameters,
342342
for 'application/x-www-form-urlencoded', 'multipart/form-data'.
343-
:param auth_settings list: Auth Settings names for the request.
344-
:param response: Response data type.
345-
:param files dict: key -> filename, value -> filepath,
343+
:param response_type: Response data type.
344+
:param auth_settings: list: Auth Settings names for the request.
345+
:param files: dict: key -> filename, value -> filepath,
346346
for 'multipart/form-data'.
347-
:param async_req bool: execute request asynchronously
347+
:param async_req: bool: execute request asynchronously
348348
:param _return_http_data_only: response data without head status code
349349
and headers
350350
:param collection_formats: dict of collection formats for path, query,
@@ -511,24 +511,21 @@ def parameters_to_tuples(self, params, collection_formats):
511511
new_params.append((k, v))
512512
return new_params
513513

514-
def is_not_ascii(self, string):
515-
return any(ord(c) >= 128 for c in string)
516-
517514
def prepare_one_file(self, file_data):
518515
# type: (Union[bytes, str, file, pathlib.Path, io.BytesIO]) -> FileFieldData # noqa: F821
519516

520-
# Python 2 has no difference between Bytes and Str
521-
# So decide non-ascii string is Bytes
522-
if isinstance(file_data, bytes) and (not six.PY2 or self.is_not_ascii(file_data)):
523-
return FileFieldData("data.bin", file_data, "application/octet-stream")
524-
525517
if isinstance(file_data, str) or (not six.PY2 and isinstance(file_data, pathlib.PurePath)):
526518
with open(file_data, "rb") as f:
527519
fname = os.path.basename(f.name)
528520
file_bytes = f.read()
529521
mime_type = mimetypes.guess_type(fname)[0] or "application/octet-stream"
530522
return FileFieldData(fname, file_bytes, mime_type)
531523

524+
# Python 2 has no difference between bytes and str
525+
# Use bytearray in Python 2 to make a difference with str
526+
if isinstance(file_data, bytes) or isinstance(file_data, bytearray):
527+
return FileFieldData("data.bin", file_data, "application/octet-stream")
528+
532529
if isinstance(file_data, io.BytesIO):
533530
return FileFieldData("data.bin", file_data.read(), "application/octet-stream")
534531

@@ -687,8 +684,8 @@ def __deserialize_datetime(self, string):
687684
except ValueError:
688685
raise ApiException(reason=("Failed to parse '{0}' as datetime object".format(string)))
689686

690-
def __hasattr(self, object, name):
691-
return name in object.__class__.__dict__
687+
def __hasattr(self, obj, name):
688+
return name in obj.__class__.__dict__
692689

693690
def __deserialize_model(self, data, klass):
694691
"""Deserializes list or dict to model.

aspose_barcode_cloud/rest.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@
4747

4848

4949
class RESTResponse(io.IOBase):
50-
def __init__(self, resp):
50+
def __init__(self, resp, *args, **kwargs):
51+
super(RESTResponse, self).__init__(*args, **kwargs)
52+
5153
self.urllib3_response = resp
5254
self.status = resp.status
5355
self.reason = resp.reason
@@ -219,8 +221,8 @@ def _request(
219221
headers=headers,
220222
)
221223
elif headers["Content-Type"] == "application/octet-stream":
222-
file = post_params.pop(-1)
223-
body = file[1][1]
224+
file_data = post_params.pop(-1)
225+
body = file_data[1][1]
224226
r = self.pool_manager.request(
225227
method, url, body=body, preload_content=_preload_content, timeout=timeout, headers=headers
226228
)
@@ -255,6 +257,7 @@ def _request(
255257

256258
return r
257259

260+
# noinspection PyPep8Naming
258261
def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None):
259262
return self._request(
260263
"GET",
@@ -265,6 +268,7 @@ def GET(self, url, headers=None, query_params=None, _preload_content=True, _requ
265268
query_params=query_params,
266269
)
267270

271+
# noinspection PyPep8Naming
268272
def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None):
269273
return self._request(
270274
"HEAD",
@@ -275,6 +279,7 @@ def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _req
275279
query_params=query_params,
276280
)
277281

282+
# noinspection PyPep8Naming
278283
def OPTIONS(
279284
self,
280285
url,
@@ -296,6 +301,7 @@ def OPTIONS(
296301
body=body,
297302
)
298303

304+
# noinspection PyPep8Naming
299305
def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None):
300306
return self._request(
301307
"DELETE",
@@ -307,6 +313,7 @@ def DELETE(self, url, headers=None, query_params=None, body=None, _preload_conte
307313
body=body,
308314
)
309315

316+
# noinspection PyPep8Naming
310317
def POST(
311318
self,
312319
url,
@@ -328,6 +335,7 @@ def POST(
328335
body=body,
329336
)
330337

338+
# noinspection PyPep8Naming
331339
def PUT(
332340
self,
333341
url,
@@ -349,6 +357,7 @@ def PUT(
349357
body=body,
350358
)
351359

360+
# noinspection PyPep8Naming
352361
def PATCH(
353362
self,
354363
url,

tests/test_recognize_bytes.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import os
33
import unittest
44

5+
import six
6+
57
from aspose_barcode_cloud import PresetType, ApiClient, BarcodeApi, DecodeBarcodeType
68
from .load_configuration import TEST_CONFIGURATION
79

@@ -15,6 +17,7 @@ def setUpClass(cls):
1517

1618
cls.api = BarcodeApi(api_client=ApiClient(configuration=TEST_CONFIGURATION))
1719

20+
@unittest.skipIf(six.PY2, "Python 2 has no difference between bytes and str")
1821
def test_post_barcode_recognize_from_url_or_content_bytes(self):
1922
"""Test case for post_barcode_recognize_from_url_or_content
2023
@@ -33,6 +36,24 @@ def test_post_barcode_recognize_from_url_or_content_bytes(self):
3336
self.assertEqual(DecodeBarcodeType.PDF417, barcode.type)
3437
self.assertEqual("Aspose.BarCode for Cloud Sample", barcode.barcode_value)
3538

39+
def test_post_barcode_recognize_from_url_or_content_bytearray(self):
40+
"""Test case for post_barcode_recognize_from_url_or_content
41+
42+
Recognize barcode from bytes.
43+
"""
44+
with open(self.test_filename, "rb") as f:
45+
image_bytes = bytearray(f.read())
46+
47+
response = self.api.post_barcode_recognize_from_url_or_content(
48+
preset=PresetType.HIGHPERFORMANCE,
49+
image=image_bytes,
50+
)
51+
52+
self.assertEqual(1, len(response.barcodes))
53+
barcode = response.barcodes[0]
54+
self.assertEqual(DecodeBarcodeType.PDF417, barcode.type)
55+
self.assertEqual("Aspose.BarCode for Cloud Sample", barcode.barcode_value)
56+
3657
def test_post_barcode_recognize_from_url_or_content_BytesIO(self):
3758
"""Test case for post_barcode_recognize_from_url_or_content
3859

tests/test_recognize_file.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import os
22
import sys
3+
import unittest
34

45
import six
5-
import unittest
66

77
from aspose_barcode_cloud import PresetType, ApiClient, BarcodeApi, DecodeBarcodeType
88
from .load_configuration import TEST_CONFIGURATION

0 commit comments

Comments
 (0)