From 77053ce944c11b1bae67cee387275e9f36d8d049 Mon Sep 17 00:00:00 2001 From: Oleg Broytman Date: Fri, 10 Nov 2023 18:17:15 +0300 Subject: [PATCH] Protect `import cgi` Module `cgi` was declared obsolete in Python 3.11 and will be removed in 3.13. Fixes: #175. --- src/formencode/validators.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/formencode/validators.py b/src/formencode/validators.py index f2011b4..6f272b7 100644 --- a/src/formencode/validators.py +++ b/src/formencode/validators.py @@ -5,7 +5,10 @@ Validator/Converters for use with FormEncode. """ -import cgi +try: + import cgi +except ImportError: # Python >= 3.13 + cgi = None import re import warnings from encodings import idna @@ -1772,7 +1775,7 @@ class FieldStorageUploadConverter(FancyValidator): no upload was given). """ def _convert_to_python(self, value, state=None): - if isinstance(value, cgi.FieldStorage): + if cgi and isinstance(value, cgi.FieldStorage): if getattr(value, 'filename', None): return value raise Invalid('invalid', value, state) @@ -1780,7 +1783,7 @@ def _convert_to_python(self, value, state=None): return value def is_empty(self, value): - if isinstance(value, cgi.FieldStorage): + if cgi and isinstance(value, cgi.FieldStorage): return not bool(getattr(value, 'filename', None)) return FancyValidator.is_empty(self, value) @@ -1825,7 +1828,7 @@ def _convert_to_python(self, value, state): upload = value.get(self.upload_key) static = value.get(self.static_key, '').strip() filename = content = None - if isinstance(upload, cgi.FieldStorage): + if cgi and isinstance(upload, cgi.FieldStorage): filename = upload.filename content = upload.value elif isinstance(upload, str) and upload: