コード例 #1
0
    def request_context(self, environ):
        """
        Create a new request context from a WSGI environ.

        The request context is used to push/pop the threadlocals required
        when processing the request. It also contains an initialized
        :class:`pyramid.interfaces.IRequest` instance using the registered
        :class:`pyramid.interfaces.IRequestFactory`. The context may be
        used as a context manager to control the threadlocal lifecycle:

        .. code-block:: python

            with router.request_context(environ) as request:
                ...

        Alternatively, the context may be used without the ``with`` statement
        by manually invoking its ``begin()`` and ``end()`` methods.

        .. code-block:: python

            ctx = router.request_context(environ)
            request = ctx.begin()
            try:
                ...
            finally:
                ctx.end()

        """
        request = self.request_factory(environ)
        request.registry = self.registry
        request.invoke_subrequest = self.invoke_subrequest
        extensions = self.request_extensions
        if extensions is not None:
            apply_request_extensions(request, extensions=extensions)
        return RequestContext(request)
コード例 #2
0
def get_root(app, request=None):
    """ Return a tuple composed of ``(root, closer)`` when provided a
    :term:`router` instance as the ``app`` argument.  The ``root``
    returned is the application root object.  The ``closer`` returned
    is a callable (accepting no arguments) that should be called when
    your scripting application is finished using the root.

    ``request`` is passed to the :app:`Pyramid` application root
    factory to compute the root. If ``request`` is None, a default
    will be constructed using the registry's :term:`Request Factory`
    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
    """
    registry = app.registry
    if request is None:
        request = _make_request('/', registry)
    request.registry = registry
    ctx = RequestContext(request)
    ctx.begin()
    def closer():
        ctx.end()
    root = app.root_factory(request)
    return root, closer
コード例 #3
0
def open_pyramid_request(registry: Registry, path='http://localhost') -> ContextManager[PyramidRequest]:
    request_factory = registry.queryUtility(IRequestFactory, default=Request)
    request = request_factory.blank(path)
    request.registry = registry
    apply_request_extensions(request)
    get_pyramid_root(request)
    context = RequestContext(request)
    context.begin()
    try:
        yield request
    finally:
        context.end()
コード例 #4
0
    def invoke_subrequest(self, request, use_tweens=False):
        """Obtain a response object from the Pyramid application based on
        information in the ``request`` object provided.  The ``request``
        object must be an object that implements the Pyramid request
        interface (such as a :class:`pyramid.request.Request` instance).  If
        ``use_tweens`` is ``True``, the request will be sent to the
        :term:`tween` in the tween stack closest to the request ingress.  If
        ``use_tweens`` is ``False``, the request will be sent to the main
        router handler, and no tweens will be invoked.

        See the API for pyramid.request for complete documentation.
        """
        request.registry = self.registry
        request.invoke_subrequest = self.invoke_subrequest
        extensions = self.request_extensions
        if extensions is not None:
            apply_request_extensions(request, extensions=extensions)
        with RequestContext(request):
            return self.invoke_request(request, _use_tweens=use_tweens)
コード例 #5
0
ファイル: base_task.py プロジェクト: Cykooz/pcelery
    def __call__(self, *args, **kwargs):
        if self.request.called_directly:
            return self._call_directly(*args, **kwargs)

        # This method in BaseTask called only if a task called directly.
        # Celery do not run this method if it is not customized in the sub-class.
        # So we not need to emulate base version of this method if it is not called directly.
        context = RequestContext(self.pyramid_request)
        context.begin()
        try:
            return self._wrapped_run(*args, **kwargs)
        finally:
            context.request._process_finished_callbacks()
            context.end()
コード例 #6
0
def pyramid_request_fixture(app_config):
    """
    :rtype: pyramid.request.Request
    """
    registry = app_config.registry
    request_factory = registry.queryUtility(IRequestFactory, default=Request)
    request = request_factory.blank('http://localhost')
    request.registry = registry
    apply_request_extensions(request)
    # create pyramid root
    root_factory = request.registry.queryUtility(IRootFactory,
                                                 default=DefaultRootFactory)
    root = root_factory(request)  # Initialise pyramid root
    if hasattr(root, 'set_request'):
        root.set_request(request)
    request.root = root
    context = RequestContext(request)
    context.begin()
    yield request
    request._process_finished_callbacks()
    context.end()
コード例 #7
0
def prepare(request=None, registry=None):
    """This function pushes data onto the Pyramid threadlocal stack
    (request and registry), making those objects 'current'.  It
    returns a dictionary useful for bootstrapping a Pyramid
    application in a scripting environment.

    ``request`` is passed to the :app:`Pyramid` application root
    factory to compute the root. If ``request`` is None, a default
    will be constructed using the registry's :term:`Request Factory`
    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.

    If ``registry`` is not supplied, the last registry loaded from
    :attr:`pyramid.config.global_registries` will be used. If you
    have loaded more than one :app:`Pyramid` application in the
    current process, you may not want to use the last registry
    loaded, thus you can search the ``global_registries`` and supply
    the appropriate one based on your own criteria.

    The function returns a dictionary composed of ``root``,
    ``closer``, ``registry``, ``request`` and ``root_factory``.  The
    ``root`` returned is the application's root resource object.  The
    ``closer`` returned is a callable (accepting no arguments) that
    should be called when your scripting application is finished
    using the root.  ``registry`` is the resolved registry object.
    ``request`` is the request object passed or the constructed request
    if no request is passed.  ``root_factory`` is the root factory used
    to construct the root.

    This function may be used as a context manager to call the ``closer``
    automatically:

    .. code-block:: python

       registry = config.registry
       with prepare(registry) as env:
           request = env['request']
           # ...

    .. versionchanged:: 1.8

       Added the ability to use the return value as a context manager.

    .. versionchanged:: 2.0

       Request finished callbacks added via
       :meth:`pyramid.request.Request.add_finished_callback` will be invoked
       by the ``closer``.

    """
    if registry is None:
        registry = getattr(request, 'registry', global_registries.last)
    if registry is None:
        raise ConfigurationError(
            'No valid Pyramid applications could be '
            'found, make sure one has been created '
            'before trying to activate it.'
        )
    if request is None:
        request = _make_request('/', registry)
    # NB: even though _make_request might have already set registry on
    # request, we reset it in case someone has passed in their own
    # request.
    request.registry = registry
    ctx = RequestContext(request)
    ctx.begin()
    apply_request_extensions(request)

    def closer():
        if request.finished_callbacks:
            request._process_finished_callbacks()
        ctx.end()

    root_factory = registry.queryUtility(
        IRootFactory, default=DefaultRootFactory
    )
    root = root_factory(request)
    if getattr(request, 'context', None) is None:
        request.context = root
    return AppEnvironment(
        root=root,
        closer=closer,
        registry=registry,
        request=request,
        root_factory=root_factory,
    )
コード例 #8
0
ファイル: __init__.py プロジェクト: Py-AMS/pyams-scheduler
 def _run(self, report, **kwargs):  # pylint: disable=too-many-locals
     """Task execution wrapper"""
     status = TASK_STATUS_NONE
     result = None
     # initialize ZCA hook
     registry = kwargs.pop('registry')
     manager.push({'registry': registry, 'request': None})
     config = Configurator(registry=registry)
     config.hook_zca()
     # open ZODB connection
     zodb_connection = ZODBConnection(name=kwargs.pop('zodb_name', ''))
     with zodb_connection as root:
         try:
             application_name = registry.settings.get(PYAMS_APPLICATION_SETTINGS_KEY,
                                                      PYAMS_APPLICATION_DEFAULT_NAME)
             application = root.get(application_name)
             sm = application.getSiteManager()  # pylint: disable=invalid-name
             scheduler_util = sm.get(SCHEDULER_NAME)
             task = scheduler_util.get(self.__name__)
             if task is not None:
                 set_local_registry(sm)
                 request = check_request(base_url=scheduler_util.notified_host,
                                         registry=registry, principal_id=self.principal_id)
                 request.root = application
                 with RequestContext(request):
                     if not (kwargs.get('run_immediate') or task.is_runnable()):
                         LOGGER.debug("Skipping inactive task {0}".format(task.name))
                         return status, result
                     translate = request.localizer.translate
                     tm = ITransactionManager(task)  # pylint: disable=invalid-name
                     for attempt in tm.attempts():
                         with attempt as t:  # pylint: disable=invalid-name
                             start_date = datetime.utcnow()
                             duration = 0.
                             try:
                                 registry.notify(BeforeRunJobEvent(task))
                                 (status, result) = task.run(report, **kwargs)
                                 end_date = datetime.utcnow()
                                 duration = (end_date - start_date).total_seconds()
                                 report.write('\n\nTask duration: {0}'.format(
                                     get_duration(start_date, request=request)))
                                 if scheduler_util.notified_host and (ChatMessage is not None):
                                     message = ChatMessage(
                                         request=request,
                                         host=scheduler_util.notified_host,
                                         action='notify',
                                         category='scheduler.run',
                                         status='success',
                                         source=INTERNAL_USER_ID,
                                         title=translate(_("Task execution")),
                                         message=translate(_("Task '{}' was executed without "
                                                             "error")).format(task.name),
                                         url='/'.join(('', '++etc++site',
                                                       scheduler_util.__name__, 'admin'))
                                     )
                                     message.send()
                             except:  # pylint: disable=bare-except
                                 status = TASK_STATUS_ERROR
                                 # pylint: disable=protected-access
                                 task._log_exception(report,
                                                     "An error occurred during execution of "
                                                     "task '{0}'".format(task.name))
                                 if scheduler_util.notified_host and (ChatMessage is not None):
                                     message = ChatMessage(
                                         request=request,
                                         host=scheduler_util.notified_host,
                                         action='notify',
                                         category='scheduler.run',
                                         status='danger',
                                         source=INTERNAL_USER_ID,
                                         title=translate(_("Task execution")),
                                         message=translate(_("An error occurred during "
                                                             "execution of task '{}'"
                                                             "")).format(task.name),
                                         url='/'.join(('', '++etc++site',
                                                       scheduler_util.__name__, 'admin'))
                                     )
                                     message.send()
                             registry.notify(AfterRunJobEvent(task, status, result))
                             task.store_report(report, status, start_date, duration)
                             task.send_report(report, status, registry)
                         if t.status == 'Committed':
                             break
         except:  # pylint: disable=bare-except
             self._log_exception(None, "Can't execute scheduled job {0}".format(self.name))
         tm = ITransactionManager(self, None)  # pylint: disable=invalid-name
         if tm is not None:
             tm.abort()
     return status, result
コード例 #9
0
ファイル: scripting.py プロジェクト: Pylons/pyramid
def prepare(request=None, registry=None):
    """ This function pushes data onto the Pyramid threadlocal stack
    (request and registry), making those objects 'current'.  It
    returns a dictionary useful for bootstrapping a Pyramid
    application in a scripting environment.

    ``request`` is passed to the :app:`Pyramid` application root
    factory to compute the root. If ``request`` is None, a default
    will be constructed using the registry's :term:`Request Factory`
    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.

    If ``registry`` is not supplied, the last registry loaded from
    :attr:`pyramid.config.global_registries` will be used. If you
    have loaded more than one :app:`Pyramid` application in the
    current process, you may not want to use the last registry
    loaded, thus you can search the ``global_registries`` and supply
    the appropriate one based on your own criteria.

    The function returns a dictionary composed of ``root``,
    ``closer``, ``registry``, ``request`` and ``root_factory``.  The
    ``root`` returned is the application's root resource object.  The
    ``closer`` returned is a callable (accepting no arguments) that
    should be called when your scripting application is finished
    using the root.  ``registry`` is the resolved registry object.
    ``request`` is the request object passed or the constructed request
    if no request is passed.  ``root_factory`` is the root factory used
    to construct the root.

    This function may be used as a context manager to call the ``closer``
    automatically:

    .. code-block:: python

       registry = config.registry
       with prepare(registry) as env:
           request = env['request']
           # ...

    .. versionchanged:: 1.8

       Added the ability to use the return value as a context manager.

    """
    if registry is None:
        registry = getattr(request, 'registry', global_registries.last)
    if registry is None:
        raise ConfigurationError(
            'No valid Pyramid applications could be '
            'found, make sure one has been created '
            'before trying to activate it.'
        )
    if request is None:
        request = _make_request('/', registry)
    # NB: even though _make_request might have already set registry on
    # request, we reset it in case someone has passed in their own
    # request.
    request.registry = registry
    ctx = RequestContext(request)
    ctx.begin()
    apply_request_extensions(request)

    def closer():
        ctx.end()

    root_factory = registry.queryUtility(
        IRootFactory, default=DefaultRootFactory
    )
    root = root_factory(request)
    if getattr(request, 'context', None) is None:
        request.context = root
    return AppEnvironment(
        root=root,
        closer=closer,
        registry=registry,
        request=request,
        root_factory=root_factory,
    )