imio.pyutils 1.1.4__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/CHANGES.rst +16 -0
  2. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/Makefile +2 -2
  3. imio_pyutils-1.2.0/PKG-INFO +424 -0
  4. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/batching.py +7 -1
  5. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/system.py +87 -15
  6. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/tests.py +78 -0
  7. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/utils.py +68 -20
  8. imio_pyutils-1.2.0/imio.pyutils.egg-info/PKG-INFO +424 -0
  9. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio.pyutils.egg-info/SOURCES.txt +0 -1
  10. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio.pyutils.egg-info/requires.txt +2 -0
  11. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/setup.py +5 -1
  12. imio.pyutils-1.1.4/PKG-INFO +0 -391
  13. imio.pyutils-1.1.4/imio.pyutils.egg-info/PKG-INFO +0 -391
  14. imio.pyutils-1.1.4/imio.pyutils.egg-info/entry_points.txt +0 -3
  15. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/MANIFEST.in +0 -0
  16. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/README.rst +0 -0
  17. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/__init__.py +0 -0
  18. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/__init__.py +0 -0
  19. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/bs.py +0 -0
  20. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio/pyutils/postgres.py +0 -0
  21. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio.pyutils.egg-info/dependency_links.txt +0 -0
  22. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio.pyutils.egg-info/namespace_packages.txt +0 -0
  23. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio.pyutils.egg-info/not-zip-safe +0 -0
  24. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/imio.pyutils.egg-info/top_level.txt +0 -0
  25. {imio.pyutils-1.1.4 → imio_pyutils-1.2.0}/setup.cfg +0 -0
@@ -1,6 +1,22 @@
1
1
  Changelog
2
2
  =========
3
3
 
4
+ 1.2.0 (2026-01-16)
5
+ ------------------
6
+
7
+ - Add missing `psutil` dependency
8
+ [laulaz]
9
+ - Tested with python 3.12, 3.13.
10
+ [sgeulette]
11
+ - Improved runCommand
12
+ [sgeulette]
13
+ - Improved `batching.batch_delete_files`
14
+ [sgeulette]
15
+ - Improved `system.post_request`
16
+ [sgeulette]
17
+ - Added `utils.shortuid_encode_id` and `utils.shortuid_decode_id` to encode/decode uid with shortuid.
18
+ [sgeulette]
19
+
4
20
  1.1.4 (2025-06-06)
5
21
  ------------------
6
22
 
@@ -4,7 +4,7 @@
4
4
  # The original Makefile can be found on https://github.com/IMIO/scripts-buildout
5
5
 
6
6
  SHELL=/bin/bash
7
- pythons=2.7 3.10
7
+ pythons=2.7 3.10 3.12 3.13
8
8
 
9
9
  ifeq (, $(shell which pyenv))
10
10
  $(error "pyenv command not found! Aborting")
@@ -26,7 +26,7 @@ help:
26
26
  bin/pip: .python-version ## Setups environment
27
27
  virtualenv .
28
28
  ./bin/pip install --upgrade pip
29
- ./bin/pip install pdbpp
29
+ ./bin/pip install pdbp
30
30
  ./bin/pip install -e .
31
31
 
32
32
  .PHONY: setup
@@ -0,0 +1,424 @@
1
+ Metadata-Version: 2.4
2
+ Name: imio.pyutils
3
+ Version: 1.2.0
4
+ Summary: Some python useful methods
5
+ Home-page: https://github.com/imio/imio.pyutils/
6
+ Author: IMIO
7
+ Author-email: support@imio.be
8
+ License: GPL
9
+ Project-URL: PyPI, https://pypi.python.org/pypi/imio.pyutils
10
+ Project-URL: Source, https://github.com/imio/imio.pyutils
11
+ Keywords: Python IMIO
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: License :: OSI Approved :: GNU General Public License (GPL)
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 2.7
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Dist: setuptools
21
+ Requires-Dist: future
22
+ Requires-Dist: psutil
23
+ Requires-Dist: requests
24
+ Requires-Dist: shortuuid>=0.5.0
25
+ Requires-Dist: six>=1.16.0
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: home-page
31
+ Dynamic: keywords
32
+ Dynamic: license
33
+ Dynamic: project-url
34
+ Dynamic: requires-dist
35
+ Dynamic: summary
36
+
37
+ .. image:: https://github.com/IMIO/imio.pyutils/actions/workflows/main.yml/badge.svg?branch=master
38
+ :target: https://github.com/IMIO/imio.pyutils/actions/workflows/main.yml
39
+
40
+ .. image:: https://coveralls.io/repos/github/IMIO/imio.pyutils/badge.svg
41
+ :target: https://coveralls.io/github/IMIO/imio.pyutils
42
+
43
+ .. image:: http://img.shields.io/pypi/v/imio.pyutils.svg
44
+ :alt: PyPI badge
45
+ :target: https://pypi.org/project/imio.pyutils
46
+
47
+ .. contents::
48
+
49
+ Introduction
50
+ ============
51
+
52
+ This package provides python useful methods.
53
+
54
+ It relates to following kinds of operations:
55
+
56
+ 1) System level operations (system.py)
57
+
58
+ It provides helper methods to:
59
+
60
+ * read and write files,
61
+ * read directories,
62
+ * execute commands,
63
+ * store and load list and dict,
64
+ * trace printing,
65
+ * creating temporary files,
66
+ * etc.
67
+
68
+ 2) Various python helpers (utils.py)
69
+
70
+ About:
71
+
72
+ * ordereddict and dict manipulations
73
+ * list manipulations
74
+ * duration recording
75
+
76
+ 3) BeautifulSoup methods (bs.py)
77
+
78
+ * remove elements
79
+ * remove attributes
80
+ * remove comments
81
+ * replace entire strings
82
+ * unwrap tags
83
+
84
+ 4) Postgres level operations (postgres.py). It requires psycopg2 egg !
85
+
86
+ It provides helper methods to:
87
+
88
+ * single or multiple select,
89
+ * insert, update, delete rows,
90
+ * etc.
91
+
92
+ Tests
93
+ =====
94
+
95
+ Can be run with: `bin/python -m unittest discover`
96
+
97
+ Changelog
98
+ =========
99
+
100
+ 1.2.0 (2026-01-16)
101
+ ------------------
102
+
103
+ - Add missing `psutil` dependency
104
+ [laulaz]
105
+ - Tested with python 3.12, 3.13.
106
+ [sgeulette]
107
+ - Improved runCommand
108
+ [sgeulette]
109
+ - Improved `batching.batch_delete_files`
110
+ [sgeulette]
111
+ - Improved `system.post_request`
112
+ [sgeulette]
113
+ - Added `utils.shortuid_encode_id` and `utils.shortuid_decode_id` to encode/decode uid with shortuid.
114
+ [sgeulette]
115
+
116
+ 1.1.4 (2025-06-06)
117
+ ------------------
118
+
119
+ - Fixed `IndexError` in `utils.get_ordinal_clusters` when `numbers=[]`.
120
+ [gbastien]
121
+
122
+ 1.1.3 (2025-02-05)
123
+ ------------------
124
+
125
+ - Improved datetime import in system to correct load_var evaluation.
126
+ [sgeulette]
127
+
128
+ 1.1.2 (2024-12-19)
129
+ ------------------
130
+
131
+ - Improved `batching.batch_delete_files`.
132
+ [sgeulette]
133
+
134
+ 1.1.1 (2024-09-18)
135
+ ------------------
136
+
137
+ - Generated universal wheel version.
138
+ [sgeulette]
139
+
140
+ 1.1.0 (2024-09-17)
141
+ ------------------
142
+
143
+ - Added `utils.add_key_if_value` to add a key in a dic only if value or is not None.
144
+ [sgeulette]
145
+ - Moved `batching.batch_delete_files` from imio.helpers to be used commonly.
146
+ [sgeulette]
147
+
148
+ 1.0.4 (2024-06-11)
149
+ ------------------
150
+
151
+ - Blacked files.
152
+ [sgeulette]
153
+ - Added `system.post_request` to send a POST request.
154
+ [sgeulette]
155
+
156
+ 1.0.3 (2024-05-24)
157
+ ------------------
158
+
159
+ - Fix bad release for python2.
160
+ [aduchene]
161
+
162
+ 1.0.2 (2024-05-15)
163
+ ------------------
164
+
165
+ - Added a new helper `utils.get_ordinal_clusters` to cluster ordinal numbers based on an offset.
166
+ [aduchene]
167
+
168
+ 1.0.1 (2024-04-08)
169
+ ------------------
170
+
171
+ - Added patterns parameter in `system.read_dir_filter`.
172
+ [sgeulette]
173
+ - Returned original filename in `system.hashed_filename` if string to hash is empty.
174
+ [sgeulette]
175
+
176
+ 1.0.0 (2024-03-05)
177
+ ------------------
178
+
179
+ - Require `six>=1.16.0`.
180
+ [sgeulette]
181
+ - Added `system.hashed_filename` to get a new filename differentiated by a hashed string.
182
+ [sgeulette]
183
+
184
+ 1.0.0a1 (2024-02-08)
185
+ --------------------
186
+
187
+ - Handled set in `load_var`.
188
+ [sgeulette]
189
+ - Added `load_pickle` and `dump_pickle`
190
+ [sgeulette]
191
+ - Improved `bs.is_empty`
192
+ [sgeulette]
193
+
194
+ 1.0.0a (2023-11-28)
195
+ -------------------
196
+
197
+ - Made py2 and py3 compliant
198
+ [sgeulette]
199
+ - Improved `utils_safe_encode`
200
+ [sgeulette]
201
+ - Added `bs.is_empty` function.
202
+ [sgeulette]
203
+ - Added `bs.remove_some_childrens` function.
204
+ [sgeulette]
205
+ - Added `bs.replace_strings_by_pattern` function
206
+ [sgeulette]
207
+ - Added `exclude_patterns` parameter in `system.read_recursive_dir`
208
+ [sgeulette]
209
+
210
+ 0.31 (2023-09-26)
211
+ -----------------
212
+
213
+ - Added `utils.listify` that will make sure a given value
214
+ is always returned as list-like iterable.
215
+ [gbastien]
216
+ - Improved `system.get_git_tag` with new parameter to get last tag from all branches
217
+ [sgeulette]
218
+ - Added `utils.radix_like_starting_1` to get list of positional numbers following a given base but starting with 1
219
+ [sgeulette]
220
+ - Added `utils.letters_sequence` to get a letters string corresponding to nth position
221
+ [sgeulette]
222
+
223
+ 0.30 (2023-07-24)
224
+ -----------------
225
+
226
+ - Added `system.read_recursive_dir` to get files recursively (with relative or full name).
227
+ [sgeulette]
228
+
229
+ 0.29 (2023-05-12)
230
+ -----------------
231
+
232
+ - Improved `utils.all_of_dict_values` to include optionally a label.
233
+ [sgeulette]
234
+ - Added `setup_logger` to modify a given logger independently
235
+ [sgeulette]
236
+ - Added `full_path` to prefix filename with path if necessary
237
+ [sgeulette]
238
+
239
+ 0.28 (2023-03-29)
240
+ -----------------
241
+
242
+ - Added `utils.one_of_dict_values` that gives the first non empty value of a list of keys.
243
+ [sgeulette]
244
+ - Added `utils.all_of_dict_values` that returns a not empty values list from a dict following a keys list
245
+ [sgeulette]
246
+
247
+ 0.27 (2023-02-27)
248
+ -----------------
249
+
250
+ - Added `utils.sort_by_indexes` that will sort a list of values
251
+ depending on a list of indexes.
252
+ [gbastien]
253
+
254
+ 0.26 (2022-12-12)
255
+ -----------------
256
+
257
+ - Added `stop` to print error and exit.
258
+ [sgeulette]
259
+
260
+ 0.25 (2022-09-16)
261
+ -----------------
262
+
263
+ - Added `get_git_tag`.
264
+ [sgeulette]
265
+
266
+ 0.24 (2022-08-19)
267
+ -----------------
268
+
269
+ - Added `utils.time_start` and `utils.time_elapsed` to print elapsed time from start.
270
+ Intended to be easily used when debugging...
271
+ [sgeulette]
272
+
273
+ 0.23 (2022-07-01)
274
+ -----------------
275
+
276
+ - Added `utils.append` to append a value and return it.
277
+ [sgeulette]
278
+
279
+ 0.22 (2022-04-28)
280
+ -----------------
281
+
282
+ - Added `utils.get_clusters` to display a list of number grouped by clusters.
283
+ [gbastien]
284
+
285
+ 0.21 (2022-04-26)
286
+ -----------------
287
+
288
+ - Added `utils.merge_dicts` to be able to merge several dicts for which values
289
+ are list, list are extended in final result.
290
+ [gbastien]
291
+
292
+ 0.20 (2022-02-10)
293
+ -----------------
294
+
295
+ - Modified `memory` to return more useful information.
296
+ [sgeulette]
297
+
298
+ 0.19 (2022-01-21)
299
+ -----------------
300
+
301
+ - Added `process_memory` to return current process memory.
302
+ [sgeulette]
303
+ - Added `memory` to return RAM information.
304
+ [sgeulette]
305
+
306
+ 0.18 (2022-01-12)
307
+ -----------------
308
+
309
+ - Made `insert_in_ordereddict` python3 compatible.
310
+ [sgeulette]
311
+ - Added `odict_pos_key` to get key at position in ordereddict.
312
+ [sgeulette]
313
+
314
+ 0.17 (2022-01-04)
315
+ -----------------
316
+
317
+ - Added `timed` and `ftimed` functions.
318
+ [sgeulette]
319
+ - Added OrderedDict for load_var function
320
+ [sgeulette]
321
+
322
+ 0.16 (2021-10-27)
323
+ -----------------
324
+
325
+ - Added `iterable_as_list_of_list` function.
326
+ [sgeulette]
327
+ - Added date in runCommand output
328
+ [sgeulette]
329
+
330
+ 0.15 (2021-04-27)
331
+ -----------------
332
+
333
+ - Added `ln_key` parameter in `read_dictcsv` method.
334
+ [sgeulette]
335
+
336
+ 0.14 (2021-04-21)
337
+ -----------------
338
+
339
+ - Added `read_dictcsv` function.
340
+ [sgeulette]
341
+ - Added `utils.replace_in_list` function to ease replacement of values in a list.
342
+ [gbastien]
343
+ - Added `safe_encode` function.
344
+ [sgeulette]
345
+
346
+ 0.13 (2020-10-07)
347
+ -----------------
348
+
349
+ - Added `insert_in_ordereddict` function to easier insert a new key at needed position.
350
+ [sgeulette]
351
+
352
+ 0.12 (2020-05-19)
353
+ -----------------
354
+
355
+ - Update syntax for py 3.
356
+ [odelaere]
357
+
358
+ 0.11 (2018-10-12)
359
+ -----------------
360
+
361
+ - Added warning log level function
362
+ [odelaere]
363
+
364
+ 0.10 (2018-07-23)
365
+ -----------------
366
+
367
+ - Added to_skip parameter in read_dir functions.
368
+ [sgeulette]
369
+
370
+ 0.9 (2017-07-28)
371
+ ----------------
372
+
373
+ - Added read_csv function.
374
+ [sgeulette]
375
+
376
+ 0.8 (2017-07-19)
377
+ ----------------
378
+
379
+ - runCommand can append to file.
380
+ [sgeulette]
381
+
382
+ 0.7 (2017-06-26)
383
+ ----------------
384
+
385
+ - Just release on pypi for collective.documentgenerator.
386
+ [sgeulette]
387
+
388
+ 0.6 (2017-02-08)
389
+ ----------------
390
+
391
+ - runCommand: return as third value the return code of the command.
392
+ [sgeulette]
393
+
394
+ 0.5 (2017-02-08)
395
+ ----------------
396
+
397
+ - Added outfile parameter to runCommand.
398
+ [sgeulette]
399
+
400
+ 0.4 (2016-12-07)
401
+ ----------------
402
+
403
+ - Added param to get only files in dir.
404
+ [sgeulette]
405
+ - Added methods for bs4 (beautifulsoup)
406
+ [sgeulette]
407
+
408
+ 0.3 (2016-09-21)
409
+ ----------------
410
+
411
+ - Return empty list when file doesn't exist.
412
+ [sgeulette]
413
+
414
+ 0.2 (2016-04-15)
415
+ ----------------
416
+
417
+ - Added options on read_file.
418
+ [sgeulette]
419
+
420
+ 0.1 (2015-06-03)
421
+ ----------------
422
+
423
+ - Initial release.
424
+ [sgeulette]
@@ -19,7 +19,7 @@ logger = logging.getLogger("imio.pyutils")
19
19
 
20
20
 
21
21
  # 7) when all the items are treated, we can delete the dictionary file
22
- def batch_delete_files(batch_keys, config, rename=True):
22
+ def batch_delete_files(batch_keys, config, rename=True, log=False):
23
23
  """Deletes the file containing the batched keys.
24
24
 
25
25
  :param batch_keys: the treated keys set
@@ -27,6 +27,7 @@ def batch_delete_files(batch_keys, config, rename=True):
27
27
  'lc': loop_count, 'pf': infile, 'cf': config_file, 'kc': keys_count, 'lk': last_key,
28
28
  'ldk': last_dump_key, 'fr'; first_run_bool}
29
29
  :param rename: do not delete but rename
30
+ :param log: if True, log action
30
31
  """
31
32
  if batch_keys is None:
32
33
  return
@@ -36,7 +37,12 @@ def batch_delete_files(batch_keys, config, rename=True):
36
37
  for filename in files:
37
38
  if rename:
38
39
  os.rename(filename, "{}.{}".format(filename, datetime.now().strftime("%Y%m%d-%H%M%S")))
40
+ msg = 'BATCHING ended: renamed file "%s" to "%s.%s"' % (filename, filename,
41
+ datetime.now().strftime("%Y%m%d-%H%M%S"))
39
42
  else:
40
43
  os.remove(filename)
44
+ msg = '"BATCHING ended: deleted file "%s""' % filename
45
+ if log:
46
+ logger.info(msg)
41
47
  except Exception as error:
42
48
  logger.exception("Error while renaming/deleting the file %s: %s", filename, error)
@@ -12,6 +12,7 @@ from six.moves import range
12
12
 
13
13
  import datetime # do not import datetime datetime because load_var must eval datetime.datetime(2024, 12, 19, 11, 34)
14
14
  import hashlib
15
+ import logging
15
16
  import os
16
17
  import re
17
18
  import requests
@@ -194,7 +195,15 @@ def read_dir(dirpath, with_path=False, only_folders=False, only_files=False, to_
194
195
 
195
196
 
196
197
  def read_recursive_dir(root_dir, rel_dir, with_folder=False, with_full_path=False, exclude_patterns=[]):
197
- """Read the dir and return files"""
198
+ """Read the dir and return files.
199
+
200
+ :param root_dir: the root directory
201
+ :param rel_dir: the relative directory to root_dir
202
+ :param with_folder: if True, include folder names in the result
203
+ :param with_full_path: if True, return full paths, else relative to root_dir
204
+ :param exclude_patterns: list of regex patterns to exclude files or folders matching them
205
+ :return: list of files
206
+ """
198
207
  files = []
199
208
  full_dir = os.path.join(root_dir, rel_dir)
200
209
  for filename in os.listdir(full_dir):
@@ -286,12 +295,14 @@ def runCommand(cmd, outfile=None, append=True):
286
295
 
287
296
  os.system(cmd + ' >_cmd_pv.out 2>_cmd_pv.err ;echo "RET_CODE=$?" >> _cmd_pv.out')
288
297
  stdout = stderr = []
298
+ ret_code = 1
289
299
  try:
290
300
  if os.path.exists("_cmd_pv.out"):
291
301
  ofile = open("_cmd_pv.out", "r")
292
302
  stdout = ofile.readlines()
293
303
  ofile.close()
294
304
  os.remove("_cmd_pv.out")
305
+ ret_code = get_ret_code(stdout.pop())
295
306
  else:
296
307
  error("File %s does not exist" % "_cmd_pv.out")
297
308
  except IOError:
@@ -306,7 +317,7 @@ def runCommand(cmd, outfile=None, append=True):
306
317
  error("File %s does not exist" % "_cmd_pv.err")
307
318
  except IOError:
308
319
  error("Cannot open %s file" % "_cmd_pv.err")
309
- return stdout, stderr, get_ret_code(stdout.pop())
320
+ return stdout, stderr, ret_code
310
321
 
311
322
 
312
323
  def full_path(path, filename):
@@ -410,7 +421,7 @@ def create_temporary_file(initial_file, file_name):
410
421
 
411
422
  def get_git_tag(path, last=False):
412
423
  if last: # from all branches
413
- cmd = "git --git-dir={0}/.git describe --tags `git --git-dir={0}/.git rev-list --tags " "--max-count=1`".format(
424
+ cmd = "git --git-dir={0}/.git describe --tags `git --git-dir={0}/.git rev-list --tags --max-count=1`".format(
414
425
  path
415
426
  )
416
427
  else: # current branch only
@@ -434,26 +445,87 @@ def get_temporary_filename(file_name):
434
445
  return temp_filename
435
446
 
436
447
 
437
- def post_request(url, data=None, json=None, headers=None):
448
+ def post_request(url, data=None, json=None, headers=None, files=None, return_json=False, logger=None,
449
+ clean_files_for_logging=True):
438
450
  """Post data to url.
439
451
 
440
452
  :param url: the url to post to
441
- :param data: a dict to consider
453
+ :param data: a data struct to consider
442
454
  :param json: a json serializable object
443
- :param headers: headers to use"""
444
- kwargs = {
445
- "headers": headers or {"Content-Type": "application/json"}
446
- if json
447
- else {"Content-Type": "application/x-www-form-urlencoded"}
448
- }
455
+ :param headers: headers to use
456
+ :param files: files to upload (dict or list of tuples)
457
+ :param return_json: response as json
458
+ :param logger: current logger, otherwise a default one is created
459
+ :param clean_files_for_logging: cleans files content for logging if True
460
+ :return: the response object
461
+ """
462
+ if json is not None and (data is not None or files is not None):
463
+ raise ValueError("Cannot use both json and data or files parameters")
464
+ if logger is None:
465
+ logger = logging.getLogger("imio.pyutils")
466
+ kwargs = {}
467
+
468
+ if files:
469
+ kwargs["files"] = files
470
+ if headers:
471
+ # Exclude Content-Type with multipart/form-data
472
+ kwargs["headers"] = {k: v for k, v in headers.items() if k.lower() != "content-type"}
473
+ if "headers" not in kwargs:
474
+ kwargs["headers"] = headers or (
475
+ {"Content-Type": "application/json"} if json else {"Content-Type": "application/x-www-form-urlencoded"}
476
+ )
449
477
  if json:
450
478
  kwargs["json"] = json
451
479
  else:
452
480
  kwargs["data"] = data
453
- with requests.post(url, **kwargs) as response:
454
- if response.status_code != 200:
455
- error("Error while posting data '%s' to '%s': %s" % (kwargs, url, response.text))
456
- return response
481
+
482
+ try:
483
+ with requests.post(url, **kwargs) as response:
484
+ if not response.ok:
485
+ if files and clean_files_for_logging:
486
+ cleaned_files = []
487
+ # clean only if item is of this format ("files", (filename, file_content))
488
+ for item in kwargs["files"]:
489
+ if isinstance(item, tuple) and len(item) == 2 and isinstance(item[1], tuple):
490
+ if len(item[1]) == 2:
491
+ cleaned_files.append((item[0], (item[1][0], len(item[1][1]))))
492
+ elif len(item[1]) == 3:
493
+ cleaned_files.append((item[0], (item[1][0], len(item[1][1]), item[1][2])))
494
+ else:
495
+ cleaned_files.append(item)
496
+ else:
497
+ cleaned_files.append(item)
498
+ kwargs["files"] = cleaned_files
499
+ if response.status_code in (401, 403):
500
+ logger.error("Authentication error while posting data to '%s': %s (status %d)"
501
+ % (url, response.text, response.status_code))
502
+ else:
503
+ logger.error("Error while posting data '%s' to '%s': %s" % (kwargs, url, response.text))
504
+ elif return_json:
505
+ try:
506
+ return response.json()
507
+ except ValueError as e:
508
+ logger.error("Error parsing JSON response from '%s': %s" % (url, str(e)))
509
+ return response
510
+ else:
511
+ return response
512
+ return response
513
+ except requests.ConnectionError as e:
514
+ msg = "Connection error while posting data to '{}': {}".format(url, str(e))
515
+ logger.error(msg)
516
+ mock_response = requests.Response()
517
+ mock_response.status_code = 503 # service unavailable
518
+ mock_response._content = "{'error': '%s'}" % msg
519
+ mock_response.url = url
520
+ return mock_response
521
+ except Exception as e:
522
+ msg = "Unexpected error while posting data to '{}': {}".format(url, str(e))
523
+ logger.error(msg)
524
+ mock_response = requests.Response()
525
+ mock_response.status_code = 500 # Internal server error
526
+ mock_response._content = "{'error': '%s'}" % msg
527
+ mock_response.url = url
528
+ return mock_response
457
529
 
458
530
 
459
531
  def process_memory():