Updated "check_request" function to use registered request factory and be able to define a principal when creating a new request is required
authorThierry Florac <thierry.florac@onf.fr>
Thu, 10 Jan 2019 16:57:51 +0100
changeset 312 7219e0e95439
parent 311 de79354828e9
child 313 7f37f0edbe9f
Updated "check_request" function to use registered request factory and be able to define a principal when creating a new request is required
src/pyams_utils/request.py
--- a/src/pyams_utils/request.py	Wed Jan 09 12:19:10 2019 +0100
+++ b/src/pyams_utils/request.py	Thu Jan 10 16:57:51 2019 +0100
@@ -12,23 +12,20 @@
 
 __docformat__ = 'restructuredtext'
 
-
-# import standard library
 import logging
-logger = logging.getLogger('PyAMS (utils)')
 
-# import interfaces
-from pyams_utils.interfaces import MissingRequestError, ICacheKeyValue
-from pyramid.interfaces import IAuthenticationPolicy, IAuthorizationPolicy
-from zope.annotation.interfaces import IAttributeAnnotatable, IAnnotations
-
-# import packages
-from pyams_utils.registry import get_global_registry
+from pyramid.interfaces import IAuthenticationPolicy, IAuthorizationPolicy, IRequestFactory
 from pyramid.request import Request
 from pyramid.security import Allowed
-from pyramid.threadlocal import get_current_request, get_current_registry
+from pyramid.threadlocal import get_current_registry, get_current_request
+from zope.annotation.interfaces import IAnnotations, IAttributeAnnotatable
 from zope.interface import alsoProvides
 
+from pyams_utils.interfaces import ICacheKeyValue, MissingRequestError
+from pyams_utils.registry import get_global_registry
+
+
+logger = logging.getLogger('PyAMS (utils)')
 
 _marker = object()
 
@@ -166,17 +163,28 @@
         return None
 
 
-def check_request(path='/', environ=None, base_url=None, headers=None, POST=None, registry=None, **kwargs):
+def check_request(path='/', environ=None, base_url=None, headers=None,
+                  POST=None, registry=None, principal_id=None, **kwargs):
     """Get current request, or create a new blank one if missing"""
     try:
         return get_request()
     except MissingRequestError:
-        request = PyAMSRequest.blank(path, environ, base_url, headers, POST, **kwargs)
         if registry is None:
             registry = get_current_registry()
             if registry is None:
                 registry = get_global_registry()
+        factory = registry.queryUtility(IRequestFactory)
+        if factory is None:
+            factory = PyAMSRequest
+        request = factory.blank(path, environ, base_url, headers, POST, **kwargs)
         request.registry = registry
+        if principal_id is not None:
+            try:
+                from pyams_security.utility import get_principal
+            except ImportError:
+                pass
+            else:
+                request.principal = get_principal(request, principal_id)
         return request