details:   https://code.tryton.org/tryton/commit/b0c00edfceea
branch:    7.4
user:      Cédric Krier <[email protected]>
date:      Sat Jan 03 13:45:10 2026 +0100
description:
        Defer patching requests default agent when it is imported

        Importing requests module in `trytond/__init__.py` prevents the gevent 
monkey
        patch to be applied to the requests module as it is imported before.

        Closes #14461
        (grafted from f46f8037da40d5208b4d32552529d7dbca1dedea)
diffstat:

 trytond/trytond/__init__.py |  32 +++++++++++++++++++++++---------
 1 files changed, 23 insertions(+), 9 deletions(-)

diffs (55 lines):

diff -r 34ac18f5d995 -r b0c00edfceea trytond/trytond/__init__.py
--- a/trytond/trytond/__init__.py       Wed Jan 07 11:19:07 2026 +0100
+++ b/trytond/trytond/__init__.py       Sat Jan 03 13:45:10 2026 +0100
@@ -1,6 +1,8 @@
 # This file is part of Tryton.  The COPYRIGHT file at the top level of
 # this repository contains the full copyright notices and license terms.
+import importlib
 import os
+import sys
 import time
 import warnings
 from email import charset
@@ -8,11 +10,6 @@
 import __main__
 from lxml import etree, objectify
 
-try:
-    from requests import utils as requests_utils
-except ImportError:
-    requests_utils = None
-
 __version__ = "7.4.25"
 
 if not os.environ.get('TRYTOND_APPNAME'):
@@ -35,9 +32,26 @@
 objectify.set_default_parser(objectify.makeparser(resolve_entities=False))
 
 
-def default_user_agent(name="Tryton"):
-    return f"{name}/{__version__}"
+class _RequestPatchFinder:
+    def find_spec(self, fullname, path, target=None):
+        if fullname != 'requests.utils':
+            return
+        sys.meta_path.remove(self)
+        spec = importlib.util.find_spec(fullname)
+        loader = spec.loader
+        original_exec = loader.exec_module
+
+        def exec_module(module):
+            original_exec(module)
+            self._patch_requests_utils(module)
+        loader.exec_module = exec_module
+        return spec
+
+    @staticmethod
+    def _patch_requests_utils(module):
+        def default_user_agent(name="Tryton"):
+            return f"{name}/{__version__}"
+        module.default_user_agent = default_user_agent
 
 
-if requests_utils:
-    requests_utils.default_user_agent = default_user_agent
+sys.meta_path.insert(0, _RequestPatchFinder())

Reply via email to