We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
make pyramid.paster.bootstrap into a context manager
This would just improve the API such that users could automatically call the closer in a reliable way.

``` python
from pyramid.paster import bootstrap

with bootstrap('development.ini') as env:
    req = env['request']
```

This change would also affect `pyramid.scripting.prepare` which is what `bootstrap` uses under the hood to construct the `env`.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pyramid/paster.py`
Content:
```
1 import os
2 
3 from paste.deploy import (
4     loadapp,
5     appconfig,
6     )
7 
8 from pyramid.compat import configparser
9 from logging.config import fileConfig
10 from pyramid.scripting import prepare
11 
12 def get_app(config_uri, name=None, options=None, loadapp=loadapp):
13     """ Return the WSGI application named ``name`` in the PasteDeploy
14     config file specified by ``config_uri``.
15 
16     ``options``, if passed, should be a dictionary used as variable assignments
17     like ``{'http_port': 8080}``.  This is useful if e.g. ``%(http_port)s`` is
18     used in the config file.
19 
20     If the ``name`` is None, this will attempt to parse the name from
21     the ``config_uri`` string expecting the format ``inifile#name``.
22     If no name is found, the name will default to "main"."""
23     path, section = _getpathsec(config_uri, name)
24     config_name = 'config:%s' % path
25     here_dir = os.getcwd()
26 
27     app = loadapp(
28         config_name,
29         name=section,
30         relative_to=here_dir,
31         global_conf=options)
32 
33     return app
34 
35 def get_appsettings(config_uri, name=None, options=None, appconfig=appconfig):
36     """ Return a dictionary representing the key/value pairs in an ``app``
37     section within the file represented by ``config_uri``.
38 
39     ``options``, if passed, should be a dictionary used as variable assignments
40     like ``{'http_port': 8080}``.  This is useful if e.g. ``%(http_port)s`` is
41     used in the config file.
42 
43     If the ``name`` is None, this will attempt to parse the name from
44     the ``config_uri`` string expecting the format ``inifile#name``.
45     If no name is found, the name will default to "main"."""
46     path, section = _getpathsec(config_uri, name)
47     config_name = 'config:%s' % path
48     here_dir = os.getcwd()
49     return appconfig(
50         config_name,
51         name=section,
52         relative_to=here_dir,
53         global_conf=options)
54 
55 def setup_logging(config_uri, global_conf=None,
56                   fileConfig=fileConfig,
57                   configparser=configparser):
58     """
59     Set up logging via :func:`logging.config.fileConfig` with the filename
60     specified via ``config_uri`` (a string in the form
61     ``filename#sectionname``).
62 
63     ConfigParser defaults are specified for the special ``__file__``
64     and ``here`` variables, similar to PasteDeploy config loading.
65     Extra defaults can optionally be specified as a dict in ``global_conf``.
66     """
67     path, _ = _getpathsec(config_uri, None)
68     parser = configparser.ConfigParser()
69     parser.read([path])
70     if parser.has_section('loggers'):
71         config_file = os.path.abspath(path)
72         full_global_conf = dict(
73             __file__=config_file,
74             here=os.path.dirname(config_file))
75         if global_conf:
76             full_global_conf.update(global_conf)
77         return fileConfig(config_file, full_global_conf)
78 
79 def _getpathsec(config_uri, name):
80     if '#' in config_uri:
81         path, section = config_uri.split('#', 1)
82     else:
83         path, section = config_uri, 'main'
84     if name:
85         section = name
86     return path, section
87 
88 def bootstrap(config_uri, request=None, options=None):
89     """ Load a WSGI application from the PasteDeploy config file specified
90     by ``config_uri``. The environment will be configured as if it is
91     currently serving ``request``, leaving a natural environment in place
92     to write scripts that can generate URLs and utilize renderers.
93 
94     This function returns a dictionary with ``app``, ``root``, ``closer``,
95     ``request``, and ``registry`` keys.  ``app`` is the WSGI app loaded
96     (based on the ``config_uri``), ``root`` is the traversal root resource
97     of the Pyramid application, and ``closer`` is a parameterless callback
98     that may be called when your script is complete (it pops a threadlocal
99     stack).
100 
101     .. note::
102 
103        Most operations within :app:`Pyramid` expect to be invoked within the
104        context of a WSGI request, thus it's important when loading your
105        application to anchor it when executing scripts and other code that is
106        not normally invoked during active WSGI requests.
107 
108     .. note::
109 
110        For a complex config file containing multiple :app:`Pyramid`
111        applications, this function will setup the environment under the context
112        of the last-loaded :app:`Pyramid` application. You may load a specific
113        application yourself by using the lower-level functions
114        :meth:`pyramid.paster.get_app` and :meth:`pyramid.scripting.prepare` in
115        conjunction with :attr:`pyramid.config.global_registries`.
116 
117     ``config_uri`` -- specifies the PasteDeploy config file to use for the
118     interactive shell. The format is ``inifile#name``. If the name is left
119     off, ``main`` will be assumed.
120 
121     ``request`` -- specified to anchor the script to a given set of WSGI
122     parameters. For example, most people would want to specify the host,
123     scheme and port such that their script will generate URLs in relation
124     to those parameters. A request with default parameters is constructed
125     for you if none is provided. You can mutate the request's ``environ``
126     later to setup a specific host/port/scheme/etc.
127 
128     ``options`` Is passed to get_app for use as variable assignments like 
129     {'http_port': 8080} and then use %(http_port)s in the
130     config file.
131 
132     See :ref:`writing_a_script` for more information about how to use this
133     function.
134     """
135     app = get_app(config_uri, options=options)
136     env = prepare(request)
137     env['app'] = app
138     return env
139 
140
```

Path: `pyramid/scripting.py`
Content:
```
1 from pyramid.config import global_registries
2 from pyramid.exceptions import ConfigurationError
3 
4 from pyramid.interfaces import (
5     IRequestFactory,
6     IRootFactory,
7     )
8 from pyramid.request import Request
9 from pyramid.request import apply_request_extensions
10 
11 from pyramid.threadlocal import manager as threadlocal_manager
12 from pyramid.traversal import DefaultRootFactory
13 
14 def get_root(app, request=None):
15     """ Return a tuple composed of ``(root, closer)`` when provided a
16     :term:`router` instance as the ``app`` argument.  The ``root``
17     returned is the application root object.  The ``closer`` returned
18     is a callable (accepting no arguments) that should be called when
19     your scripting application is finished using the root.
20 
21     ``request`` is passed to the :app:`Pyramid` application root
22     factory to compute the root. If ``request`` is None, a default
23     will be constructed using the registry's :term:`Request Factory`
24     via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
25     """
26     registry = app.registry
27     if request is None:
28         request = _make_request('/', registry)
29     threadlocals = {'registry':registry, 'request':request}
30     app.threadlocal_manager.push(threadlocals)
31     def closer(request=request): # keep request alive via this function default
32         app.threadlocal_manager.pop()
33     root = app.root_factory(request)
34     return root, closer
35 
36 def prepare(request=None, registry=None):
37     """ This function pushes data onto the Pyramid threadlocal stack
38     (request and registry), making those objects 'current'.  It
39     returns a dictionary useful for bootstrapping a Pyramid
40     application in a scripting environment.
41 
42     ``request`` is passed to the :app:`Pyramid` application root
43     factory to compute the root. If ``request`` is None, a default
44     will be constructed using the registry's :term:`Request Factory`
45     via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
46 
47     If ``registry`` is not supplied, the last registry loaded from
48     :attr:`pyramid.config.global_registries` will be used. If you
49     have loaded more than one :app:`Pyramid` application in the
50     current process, you may not want to use the last registry
51     loaded, thus you can search the ``global_registries`` and supply
52     the appropriate one based on your own criteria.
53 
54     The function returns a dictionary composed of ``root``,
55     ``closer``, ``registry``, ``request`` and ``root_factory``.  The
56     ``root`` returned is the application's root resource object.  The
57     ``closer`` returned is a callable (accepting no arguments) that
58     should be called when your scripting application is finished
59     using the root.  ``registry`` is the registry object passed or
60     the last registry loaded into
61     :attr:`pyramid.config.global_registries` if no registry is passed.
62     ``request`` is the request object passed or the constructed request
63     if no request is passed.  ``root_factory`` is the root factory used
64     to construct the root.
65     """
66     if registry is None:
67         registry = getattr(request, 'registry', global_registries.last)
68     if registry is None:
69         raise ConfigurationError('No valid Pyramid applications could be '
70                                  'found, make sure one has been created '
71                                  'before trying to activate it.')
72     if request is None:
73         request = _make_request('/', registry)
74     # NB: even though _make_request might have already set registry on
75     # request, we reset it in case someone has passed in their own
76     # request.
77     request.registry = registry 
78     threadlocals = {'registry':registry, 'request':request}
79     threadlocal_manager.push(threadlocals)
80     apply_request_extensions(request)
81     def closer():
82         threadlocal_manager.pop()
83     root_factory = registry.queryUtility(IRootFactory,
84                                          default=DefaultRootFactory)
85     root = root_factory(request)
86     if getattr(request, 'context', None) is None:
87         request.context = root
88     return {'root':root, 'closer':closer, 'registry':registry,
89             'request':request, 'root_factory':root_factory}
90 
91 def _make_request(path, registry=None):
92     """ Return a :meth:`pyramid.request.Request` object anchored at a
93     given path. The object returned will be generated from the supplied
94     registry's :term:`Request Factory` using the
95     :meth:`pyramid.interfaces.IRequestFactory.blank` method.
96 
97     This request object can be passed to :meth:`pyramid.scripting.get_root`
98     or :meth:`pyramid.scripting.prepare` to initialize an application in
99     preparation for executing a script with a proper environment setup.
100     URLs can then be generated with the object, as well as rendering
101     templates.
102 
103     If ``registry`` is not supplied, the last registry loaded from
104     :attr:`pyramid.config.global_registries` will be used. If you have
105     loaded more than one :app:`Pyramid` application in the current
106     process, you may not want to use the last registry loaded, thus
107     you can search the ``global_registries`` and supply the appropriate
108     one based on your own criteria.
109     """
110     if registry is None:
111         registry = global_registries.last
112     request_factory = registry.queryUtility(IRequestFactory, default=Request)
113     request = request_factory.blank(path)
114     request.registry = registry
115     return request
116
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pyramid/paster.py b/pyramid/paster.py
--- a/pyramid/paster.py
+++ b/pyramid/paster.py
@@ -129,8 +129,22 @@
     {'http_port': 8080} and then use %(http_port)s in the
     config file.
 
+    This function may be used as a context manager to call the ``closer``
+    automatically:
+
+    .. code-block:: python
+
+       with bootstrap('development.ini') as env:
+           request = env['request']
+           # ...
+
     See :ref:`writing_a_script` for more information about how to use this
     function.
+
+    .. versionchanged:: 1.8
+
+       Added the ability to use the return value as a context manager.
+
     """
     app = get_app(config_uri, options=options)
     env = prepare(request)
diff --git a/pyramid/scripting.py b/pyramid/scripting.py
--- a/pyramid/scripting.py
+++ b/pyramid/scripting.py
@@ -56,12 +56,25 @@
     ``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 registry object passed or
-    the last registry loaded into
-    :attr:`pyramid.config.global_registries` if no registry is passed.
+    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)
@@ -85,8 +98,20 @@
     root = root_factory(request)
     if getattr(request, 'context', None) is None:
         request.context = root
-    return {'root':root, 'closer':closer, 'registry':registry,
-            'request':request, 'root_factory':root_factory}
+    return AppEnvironment(
+        root=root,
+        closer=closer,
+        registry=registry,
+        request=request,
+        root_factory=root_factory,
+    )
+
+class AppEnvironment(dict):
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self['closer']()
 
 def _make_request(path, registry=None):
     """ Return a :meth:`pyramid.request.Request` object anchored at a

{"golden_diff": "diff --git a/pyramid/paster.py b/pyramid/paster.py\n--- a/pyramid/paster.py\n+++ b/pyramid/paster.py\n@@ -129,8 +129,22 @@\n     {'http_port': 8080} and then use %(http_port)s in the\n     config file.\n \n+    This function may be used as a context manager to call the ``closer``\n+    automatically:\n+\n+    .. code-block:: python\n+\n+       with bootstrap('development.ini') as env:\n+           request = env['request']\n+           # ...\n+\n     See :ref:`writing_a_script` for more information about how to use this\n     function.\n+\n+    .. versionchanged:: 1.8\n+\n+       Added the ability to use the return value as a context manager.\n+\n     \"\"\"\n     app = get_app(config_uri, options=options)\n     env = prepare(request)\ndiff --git a/pyramid/scripting.py b/pyramid/scripting.py\n--- a/pyramid/scripting.py\n+++ b/pyramid/scripting.py\n@@ -56,12 +56,25 @@\n     ``root`` returned is the application's root resource object.  The\n     ``closer`` returned is a callable (accepting no arguments) that\n     should be called when your scripting application is finished\n-    using the root.  ``registry`` is the registry object passed or\n-    the last registry loaded into\n-    :attr:`pyramid.config.global_registries` if no registry is passed.\n+    using the root.  ``registry`` is the resolved registry object.\n     ``request`` is the request object passed or the constructed request\n     if no request is passed.  ``root_factory`` is the root factory used\n     to construct the root.\n+\n+    This function may be used as a context manager to call the ``closer``\n+    automatically:\n+\n+    .. code-block:: python\n+\n+       registry = config.registry\n+       with prepare(registry) as env:\n+           request = env['request']\n+           # ...\n+\n+    .. versionchanged:: 1.8\n+\n+       Added the ability to use the return value as a context manager.\n+\n     \"\"\"\n     if registry is None:\n         registry = getattr(request, 'registry', global_registries.last)\n@@ -85,8 +98,20 @@\n     root = root_factory(request)\n     if getattr(request, 'context', None) is None:\n         request.context = root\n-    return {'root':root, 'closer':closer, 'registry':registry,\n-            'request':request, 'root_factory':root_factory}\n+    return AppEnvironment(\n+        root=root,\n+        closer=closer,\n+        registry=registry,\n+        request=request,\n+        root_factory=root_factory,\n+    )\n+\n+class AppEnvironment(dict):\n+    def __enter__(self):\n+        return self\n+\n+    def __exit__(self, type, value, traceback):\n+        self['closer']()\n \n def _make_request(path, registry=None):\n     \"\"\" Return a :meth:`pyramid.request.Request` object anchored at a\n", "issue": "make pyramid.paster.bootstrap into a context manager\nThis would just improve the API such that users could automatically call the closer in a reliable way.\n\n``` python\nfrom pyramid.paster import bootstrap\n\nwith bootstrap('development.ini') as env:\n    req = env['request']\n```\n\nThis change would also affect `pyramid.scripting.prepare` which is what `bootstrap` uses under the hood to construct the `env`.\n\n", "before_files": [{"content": "import os\n\nfrom paste.deploy import (\n    loadapp,\n    appconfig,\n    )\n\nfrom pyramid.compat import configparser\nfrom logging.config import fileConfig\nfrom pyramid.scripting import prepare\n\ndef get_app(config_uri, name=None, options=None, loadapp=loadapp):\n    \"\"\" Return the WSGI application named ``name`` in the PasteDeploy\n    config file specified by ``config_uri``.\n\n    ``options``, if passed, should be a dictionary used as variable assignments\n    like ``{'http_port': 8080}``.  This is useful if e.g. ``%(http_port)s`` is\n    used in the config file.\n\n    If the ``name`` is None, this will attempt to parse the name from\n    the ``config_uri`` string expecting the format ``inifile#name``.\n    If no name is found, the name will default to \"main\".\"\"\"\n    path, section = _getpathsec(config_uri, name)\n    config_name = 'config:%s' % path\n    here_dir = os.getcwd()\n\n    app = loadapp(\n        config_name,\n        name=section,\n        relative_to=here_dir,\n        global_conf=options)\n\n    return app\n\ndef get_appsettings(config_uri, name=None, options=None, appconfig=appconfig):\n    \"\"\" Return a dictionary representing the key/value pairs in an ``app``\n    section within the file represented by ``config_uri``.\n\n    ``options``, if passed, should be a dictionary used as variable assignments\n    like ``{'http_port': 8080}``.  This is useful if e.g. ``%(http_port)s`` is\n    used in the config file.\n\n    If the ``name`` is None, this will attempt to parse the name from\n    the ``config_uri`` string expecting the format ``inifile#name``.\n    If no name is found, the name will default to \"main\".\"\"\"\n    path, section = _getpathsec(config_uri, name)\n    config_name = 'config:%s' % path\n    here_dir = os.getcwd()\n    return appconfig(\n        config_name,\n        name=section,\n        relative_to=here_dir,\n        global_conf=options)\n\ndef setup_logging(config_uri, global_conf=None,\n                  fileConfig=fileConfig,\n                  configparser=configparser):\n    \"\"\"\n    Set up logging via :func:`logging.config.fileConfig` with the filename\n    specified via ``config_uri`` (a string in the form\n    ``filename#sectionname``).\n\n    ConfigParser defaults are specified for the special ``__file__``\n    and ``here`` variables, similar to PasteDeploy config loading.\n    Extra defaults can optionally be specified as a dict in ``global_conf``.\n    \"\"\"\n    path, _ = _getpathsec(config_uri, None)\n    parser = configparser.ConfigParser()\n    parser.read([path])\n    if parser.has_section('loggers'):\n        config_file = os.path.abspath(path)\n        full_global_conf = dict(\n            __file__=config_file,\n            here=os.path.dirname(config_file))\n        if global_conf:\n            full_global_conf.update(global_conf)\n        return fileConfig(config_file, full_global_conf)\n\ndef _getpathsec(config_uri, name):\n    if '#' in config_uri:\n        path, section = config_uri.split('#', 1)\n    else:\n        path, section = config_uri, 'main'\n    if name:\n        section = name\n    return path, section\n\ndef bootstrap(config_uri, request=None, options=None):\n    \"\"\" Load a WSGI application from the PasteDeploy config file specified\n    by ``config_uri``. The environment will be configured as if it is\n    currently serving ``request``, leaving a natural environment in place\n    to write scripts that can generate URLs and utilize renderers.\n\n    This function returns a dictionary with ``app``, ``root``, ``closer``,\n    ``request``, and ``registry`` keys.  ``app`` is the WSGI app loaded\n    (based on the ``config_uri``), ``root`` is the traversal root resource\n    of the Pyramid application, and ``closer`` is a parameterless callback\n    that may be called when your script is complete (it pops a threadlocal\n    stack).\n\n    .. note::\n\n       Most operations within :app:`Pyramid` expect to be invoked within the\n       context of a WSGI request, thus it's important when loading your\n       application to anchor it when executing scripts and other code that is\n       not normally invoked during active WSGI requests.\n\n    .. note::\n\n       For a complex config file containing multiple :app:`Pyramid`\n       applications, this function will setup the environment under the context\n       of the last-loaded :app:`Pyramid` application. You may load a specific\n       application yourself by using the lower-level functions\n       :meth:`pyramid.paster.get_app` and :meth:`pyramid.scripting.prepare` in\n       conjunction with :attr:`pyramid.config.global_registries`.\n\n    ``config_uri`` -- specifies the PasteDeploy config file to use for the\n    interactive shell. The format is ``inifile#name``. If the name is left\n    off, ``main`` will be assumed.\n\n    ``request`` -- specified to anchor the script to a given set of WSGI\n    parameters. For example, most people would want to specify the host,\n    scheme and port such that their script will generate URLs in relation\n    to those parameters. A request with default parameters is constructed\n    for you if none is provided. You can mutate the request's ``environ``\n    later to setup a specific host/port/scheme/etc.\n\n    ``options`` Is passed to get_app for use as variable assignments like \n    {'http_port': 8080} and then use %(http_port)s in the\n    config file.\n\n    See :ref:`writing_a_script` for more information about how to use this\n    function.\n    \"\"\"\n    app = get_app(config_uri, options=options)\n    env = prepare(request)\n    env['app'] = app\n    return env\n\n", "path": "pyramid/paster.py"}, {"content": "from pyramid.config import global_registries\nfrom pyramid.exceptions import ConfigurationError\n\nfrom pyramid.interfaces import (\n    IRequestFactory,\n    IRootFactory,\n    )\nfrom pyramid.request import Request\nfrom pyramid.request import apply_request_extensions\n\nfrom pyramid.threadlocal import manager as threadlocal_manager\nfrom pyramid.traversal import DefaultRootFactory\n\ndef get_root(app, request=None):\n    \"\"\" Return a tuple composed of ``(root, closer)`` when provided a\n    :term:`router` instance as the ``app`` argument.  The ``root``\n    returned is the application root object.  The ``closer`` returned\n    is a callable (accepting no arguments) that should be called when\n    your scripting application is finished using the root.\n\n    ``request`` is passed to the :app:`Pyramid` application root\n    factory to compute the root. If ``request`` is None, a default\n    will be constructed using the registry's :term:`Request Factory`\n    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.\n    \"\"\"\n    registry = app.registry\n    if request is None:\n        request = _make_request('/', registry)\n    threadlocals = {'registry':registry, 'request':request}\n    app.threadlocal_manager.push(threadlocals)\n    def closer(request=request): # keep request alive via this function default\n        app.threadlocal_manager.pop()\n    root = app.root_factory(request)\n    return root, closer\n\ndef prepare(request=None, registry=None):\n    \"\"\" This function pushes data onto the Pyramid threadlocal stack\n    (request and registry), making those objects 'current'.  It\n    returns a dictionary useful for bootstrapping a Pyramid\n    application in a scripting environment.\n\n    ``request`` is passed to the :app:`Pyramid` application root\n    factory to compute the root. If ``request`` is None, a default\n    will be constructed using the registry's :term:`Request Factory`\n    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.\n\n    If ``registry`` is not supplied, the last registry loaded from\n    :attr:`pyramid.config.global_registries` will be used. If you\n    have loaded more than one :app:`Pyramid` application in the\n    current process, you may not want to use the last registry\n    loaded, thus you can search the ``global_registries`` and supply\n    the appropriate one based on your own criteria.\n\n    The function returns a dictionary composed of ``root``,\n    ``closer``, ``registry``, ``request`` and ``root_factory``.  The\n    ``root`` returned is the application's root resource object.  The\n    ``closer`` returned is a callable (accepting no arguments) that\n    should be called when your scripting application is finished\n    using the root.  ``registry`` is the registry object passed or\n    the last registry loaded into\n    :attr:`pyramid.config.global_registries` if no registry is passed.\n    ``request`` is the request object passed or the constructed request\n    if no request is passed.  ``root_factory`` is the root factory used\n    to construct the root.\n    \"\"\"\n    if registry is None:\n        registry = getattr(request, 'registry', global_registries.last)\n    if registry is None:\n        raise ConfigurationError('No valid Pyramid applications could be '\n                                 'found, make sure one has been created '\n                                 'before trying to activate it.')\n    if request is None:\n        request = _make_request('/', registry)\n    # NB: even though _make_request might have already set registry on\n    # request, we reset it in case someone has passed in their own\n    # request.\n    request.registry = registry \n    threadlocals = {'registry':registry, 'request':request}\n    threadlocal_manager.push(threadlocals)\n    apply_request_extensions(request)\n    def closer():\n        threadlocal_manager.pop()\n    root_factory = registry.queryUtility(IRootFactory,\n                                         default=DefaultRootFactory)\n    root = root_factory(request)\n    if getattr(request, 'context', None) is None:\n        request.context = root\n    return {'root':root, 'closer':closer, 'registry':registry,\n            'request':request, 'root_factory':root_factory}\n\ndef _make_request(path, registry=None):\n    \"\"\" Return a :meth:`pyramid.request.Request` object anchored at a\n    given path. The object returned will be generated from the supplied\n    registry's :term:`Request Factory` using the\n    :meth:`pyramid.interfaces.IRequestFactory.blank` method.\n\n    This request object can be passed to :meth:`pyramid.scripting.get_root`\n    or :meth:`pyramid.scripting.prepare` to initialize an application in\n    preparation for executing a script with a proper environment setup.\n    URLs can then be generated with the object, as well as rendering\n    templates.\n\n    If ``registry`` is not supplied, the last registry loaded from\n    :attr:`pyramid.config.global_registries` will be used. If you have\n    loaded more than one :app:`Pyramid` application in the current\n    process, you may not want to use the last registry loaded, thus\n    you can search the ``global_registries`` and supply the appropriate\n    one based on your own criteria.\n    \"\"\"\n    if registry is None:\n        registry = global_registries.last\n    request_factory = registry.queryUtility(IRequestFactory, default=Request)\n    request = request_factory.blank(path)\n    request.registry = registry\n    return request\n", "path": "pyramid/scripting.py"}], "after_files": [{"content": "import os\n\nfrom paste.deploy import (\n    loadapp,\n    appconfig,\n    )\n\nfrom pyramid.compat import configparser\nfrom logging.config import fileConfig\nfrom pyramid.scripting import prepare\n\ndef get_app(config_uri, name=None, options=None, loadapp=loadapp):\n    \"\"\" Return the WSGI application named ``name`` in the PasteDeploy\n    config file specified by ``config_uri``.\n\n    ``options``, if passed, should be a dictionary used as variable assignments\n    like ``{'http_port': 8080}``.  This is useful if e.g. ``%(http_port)s`` is\n    used in the config file.\n\n    If the ``name`` is None, this will attempt to parse the name from\n    the ``config_uri`` string expecting the format ``inifile#name``.\n    If no name is found, the name will default to \"main\".\"\"\"\n    path, section = _getpathsec(config_uri, name)\n    config_name = 'config:%s' % path\n    here_dir = os.getcwd()\n\n    app = loadapp(\n        config_name,\n        name=section,\n        relative_to=here_dir,\n        global_conf=options)\n\n    return app\n\ndef get_appsettings(config_uri, name=None, options=None, appconfig=appconfig):\n    \"\"\" Return a dictionary representing the key/value pairs in an ``app``\n    section within the file represented by ``config_uri``.\n\n    ``options``, if passed, should be a dictionary used as variable assignments\n    like ``{'http_port': 8080}``.  This is useful if e.g. ``%(http_port)s`` is\n    used in the config file.\n\n    If the ``name`` is None, this will attempt to parse the name from\n    the ``config_uri`` string expecting the format ``inifile#name``.\n    If no name is found, the name will default to \"main\".\"\"\"\n    path, section = _getpathsec(config_uri, name)\n    config_name = 'config:%s' % path\n    here_dir = os.getcwd()\n    return appconfig(\n        config_name,\n        name=section,\n        relative_to=here_dir,\n        global_conf=options)\n\ndef setup_logging(config_uri, global_conf=None,\n                  fileConfig=fileConfig,\n                  configparser=configparser):\n    \"\"\"\n    Set up logging via :func:`logging.config.fileConfig` with the filename\n    specified via ``config_uri`` (a string in the form\n    ``filename#sectionname``).\n\n    ConfigParser defaults are specified for the special ``__file__``\n    and ``here`` variables, similar to PasteDeploy config loading.\n    Extra defaults can optionally be specified as a dict in ``global_conf``.\n    \"\"\"\n    path, _ = _getpathsec(config_uri, None)\n    parser = configparser.ConfigParser()\n    parser.read([path])\n    if parser.has_section('loggers'):\n        config_file = os.path.abspath(path)\n        full_global_conf = dict(\n            __file__=config_file,\n            here=os.path.dirname(config_file))\n        if global_conf:\n            full_global_conf.update(global_conf)\n        return fileConfig(config_file, full_global_conf)\n\ndef _getpathsec(config_uri, name):\n    if '#' in config_uri:\n        path, section = config_uri.split('#', 1)\n    else:\n        path, section = config_uri, 'main'\n    if name:\n        section = name\n    return path, section\n\ndef bootstrap(config_uri, request=None, options=None):\n    \"\"\" Load a WSGI application from the PasteDeploy config file specified\n    by ``config_uri``. The environment will be configured as if it is\n    currently serving ``request``, leaving a natural environment in place\n    to write scripts that can generate URLs and utilize renderers.\n\n    This function returns a dictionary with ``app``, ``root``, ``closer``,\n    ``request``, and ``registry`` keys.  ``app`` is the WSGI app loaded\n    (based on the ``config_uri``), ``root`` is the traversal root resource\n    of the Pyramid application, and ``closer`` is a parameterless callback\n    that may be called when your script is complete (it pops a threadlocal\n    stack).\n\n    .. note::\n\n       Most operations within :app:`Pyramid` expect to be invoked within the\n       context of a WSGI request, thus it's important when loading your\n       application to anchor it when executing scripts and other code that is\n       not normally invoked during active WSGI requests.\n\n    .. note::\n\n       For a complex config file containing multiple :app:`Pyramid`\n       applications, this function will setup the environment under the context\n       of the last-loaded :app:`Pyramid` application. You may load a specific\n       application yourself by using the lower-level functions\n       :meth:`pyramid.paster.get_app` and :meth:`pyramid.scripting.prepare` in\n       conjunction with :attr:`pyramid.config.global_registries`.\n\n    ``config_uri`` -- specifies the PasteDeploy config file to use for the\n    interactive shell. The format is ``inifile#name``. If the name is left\n    off, ``main`` will be assumed.\n\n    ``request`` -- specified to anchor the script to a given set of WSGI\n    parameters. For example, most people would want to specify the host,\n    scheme and port such that their script will generate URLs in relation\n    to those parameters. A request with default parameters is constructed\n    for you if none is provided. You can mutate the request's ``environ``\n    later to setup a specific host/port/scheme/etc.\n\n    ``options`` Is passed to get_app for use as variable assignments like \n    {'http_port': 8080} and then use %(http_port)s in the\n    config file.\n\n    This function may be used as a context manager to call the ``closer``\n    automatically:\n\n    .. code-block:: python\n\n       with bootstrap('development.ini') as env:\n           request = env['request']\n           # ...\n\n    See :ref:`writing_a_script` for more information about how to use this\n    function.\n\n    .. versionchanged:: 1.8\n\n       Added the ability to use the return value as a context manager.\n\n    \"\"\"\n    app = get_app(config_uri, options=options)\n    env = prepare(request)\n    env['app'] = app\n    return env\n\n", "path": "pyramid/paster.py"}, {"content": "from pyramid.config import global_registries\nfrom pyramid.exceptions import ConfigurationError\n\nfrom pyramid.interfaces import (\n    IRequestFactory,\n    IRootFactory,\n    )\nfrom pyramid.request import Request\nfrom pyramid.request import apply_request_extensions\n\nfrom pyramid.threadlocal import manager as threadlocal_manager\nfrom pyramid.traversal import DefaultRootFactory\n\ndef get_root(app, request=None):\n    \"\"\" Return a tuple composed of ``(root, closer)`` when provided a\n    :term:`router` instance as the ``app`` argument.  The ``root``\n    returned is the application root object.  The ``closer`` returned\n    is a callable (accepting no arguments) that should be called when\n    your scripting application is finished using the root.\n\n    ``request`` is passed to the :app:`Pyramid` application root\n    factory to compute the root. If ``request`` is None, a default\n    will be constructed using the registry's :term:`Request Factory`\n    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.\n    \"\"\"\n    registry = app.registry\n    if request is None:\n        request = _make_request('/', registry)\n    threadlocals = {'registry':registry, 'request':request}\n    app.threadlocal_manager.push(threadlocals)\n    def closer(request=request): # keep request alive via this function default\n        app.threadlocal_manager.pop()\n    root = app.root_factory(request)\n    return root, closer\n\ndef prepare(request=None, registry=None):\n    \"\"\" This function pushes data onto the Pyramid threadlocal stack\n    (request and registry), making those objects 'current'.  It\n    returns a dictionary useful for bootstrapping a Pyramid\n    application in a scripting environment.\n\n    ``request`` is passed to the :app:`Pyramid` application root\n    factory to compute the root. If ``request`` is None, a default\n    will be constructed using the registry's :term:`Request Factory`\n    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.\n\n    If ``registry`` is not supplied, the last registry loaded from\n    :attr:`pyramid.config.global_registries` will be used. If you\n    have loaded more than one :app:`Pyramid` application in the\n    current process, you may not want to use the last registry\n    loaded, thus you can search the ``global_registries`` and supply\n    the appropriate one based on your own criteria.\n\n    The function returns a dictionary composed of ``root``,\n    ``closer``, ``registry``, ``request`` and ``root_factory``.  The\n    ``root`` returned is the application's root resource object.  The\n    ``closer`` returned is a callable (accepting no arguments) that\n    should be called when your scripting application is finished\n    using the root.  ``registry`` is the resolved registry object.\n    ``request`` is the request object passed or the constructed request\n    if no request is passed.  ``root_factory`` is the root factory used\n    to construct the root.\n\n    This function may be used as a context manager to call the ``closer``\n    automatically:\n\n    .. code-block:: python\n\n       registry = config.registry\n       with prepare(registry) as env:\n           request = env['request']\n           # ...\n\n    .. versionchanged:: 1.8\n\n       Added the ability to use the return value as a context manager.\n\n    \"\"\"\n    if registry is None:\n        registry = getattr(request, 'registry', global_registries.last)\n    if registry is None:\n        raise ConfigurationError('No valid Pyramid applications could be '\n                                 'found, make sure one has been created '\n                                 'before trying to activate it.')\n    if request is None:\n        request = _make_request('/', registry)\n    # NB: even though _make_request might have already set registry on\n    # request, we reset it in case someone has passed in their own\n    # request.\n    request.registry = registry \n    threadlocals = {'registry':registry, 'request':request}\n    threadlocal_manager.push(threadlocals)\n    apply_request_extensions(request)\n    def closer():\n        threadlocal_manager.pop()\n    root_factory = registry.queryUtility(IRootFactory,\n                                         default=DefaultRootFactory)\n    root = root_factory(request)\n    if getattr(request, 'context', None) is None:\n        request.context = root\n    return AppEnvironment(\n        root=root,\n        closer=closer,\n        registry=registry,\n        request=request,\n        root_factory=root_factory,\n    )\n\nclass AppEnvironment(dict):\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        self['closer']()\n\ndef _make_request(path, registry=None):\n    \"\"\" Return a :meth:`pyramid.request.Request` object anchored at a\n    given path. The object returned will be generated from the supplied\n    registry's :term:`Request Factory` using the\n    :meth:`pyramid.interfaces.IRequestFactory.blank` method.\n\n    This request object can be passed to :meth:`pyramid.scripting.get_root`\n    or :meth:`pyramid.scripting.prepare` to initialize an application in\n    preparation for executing a script with a proper environment setup.\n    URLs can then be generated with the object, as well as rendering\n    templates.\n\n    If ``registry`` is not supplied, the last registry loaded from\n    :attr:`pyramid.config.global_registries` will be used. If you have\n    loaded more than one :app:`Pyramid` application in the current\n    process, you may not want to use the last registry loaded, thus\n    you can search the ``global_registries`` and supply the appropriate\n    one based on your own criteria.\n    \"\"\"\n    if registry is None:\n        registry = global_registries.last\n    request_factory = registry.queryUtility(IRequestFactory, default=Request)\n    request = request_factory.blank(path)\n    request.registry = registry\n    return request\n", "path": "pyramid/scripting.py"}]}