src/pyams_utils/request.py
changeset 1 3f89629b9e54
child 21 b1b92e017581
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/request.py	Thu Feb 19 00:46:48 2015 +0100
@@ -0,0 +1,80 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from zope.annotation.interfaces import IAttributeAnnotatable, IAnnotations
+from zope.security.interfaces import NoInteraction
+
+# import packages
+from pyramid.request import Request
+from pyramid.threadlocal import get_current_request
+from zope.interface import alsoProvides
+
+
+def get_request(raise_exception=True):
+    """Get current request
+
+    Raises a NoInteraction exception if there is no active request"""
+    request = get_current_request()
+    if (request is None) and raise_exception:
+        raise NoInteraction("No request")
+    return request
+
+
+def query_request():
+    """Query current request
+
+    Returns None if there is no active request"""
+    try:
+        return get_request()
+    except NoInteraction:
+        return None
+
+
+def check_request(path='/', environ=None, base_url=None, headers=None, POST=None, **kw):
+    """Get current request, or create a new blank one if missing"""
+    try:
+        return get_request()
+    except NoInteraction:
+        return Request.blank(path, environ, base_url, headers, POST, **kw)
+
+
+def get_annotations(request):
+    """Define 'annotations' request property"""
+    alsoProvides(request, IAttributeAnnotatable)
+    return IAnnotations(request)
+
+
+def get_debug(request):
+    """Define 'debug' request property"""
+    class Debug():
+        def __init__(self):
+            self.showTAL = False
+            self.sourceAnnotations = False
+    return Debug()
+
+
+def get_request_data(request, key, default=None):
+    """Get data associated with request"""
+    annotations = request.annotations
+    return annotations.get(key, default)
+
+
+def set_request_data(request, key, value):
+    """Associate data with request"""
+    annotations = request.annotations
+    annotations[key] = value