def registerSettings(dictarg=None, **kw): """Register one or more 'setting' key/value pairs. A setting is a single key/value pair in the dictionary-ish object returned from the API :attr:`pyramid.registry.Registry.settings`. You may pass a dictionary:: registerSettings({'external_uri':'http://example.com'}) Or a set of key/value pairs:: registerSettings(external_uri='http://example.com') Use of this function is required when you need to test code that calls the :attr:`pyramid.registry.Registry.settings` API and which uses return values from that API. .. warning:: This API is deprecated as of :app:`Pyramid` 1.0. Instead use the :meth:`pyramid.configuration.Configurator.add_settings` method in your unit and integration tests. """ registry = get_current_registry() config = Configurator(registry=registry) config.add_settings(dictarg, **kw)
def registerEventListener(event_iface=None): """ Registers an :term:`event` listener (aka :term:`subscriber`) listening for events of the type ``event_iface``. This method returns a list object which is appended to by the subscriber whenever an event is captured. When an event is dispatched that matches ``event_iface``, that event will be appended to the list. You can then compare the values in the list to expected event notifications. This method is useful when testing code that wants to call :meth:`pyramid.registry.Registry.notify`, :func:`zope.component.event.dispatch` or :func:`zope.component.event.objectEventNotify`. The default value of ``event_iface`` (``None``) implies a subscriber registered for *any* kind of event. .. warning:: This API is deprecated as of :app:`Pyramid` 1.0. Instead use the :meth:`pyramid.configuration.Configurator.testing_add_subscriber` method in your unit and integration tests. """ registry = get_current_registry() config = Configurator(registry=registry) return config.testing_add_subscriber(event_iface)
class TestSubscriber(unittest.TestCase): def setUp(self): registry = DummyRegistry() from pyramid.configuration import Configurator self.config = Configurator(registry) self.config.begin() def tearDown(self): self.config.end() def _makeOne(self, *ifaces): from pyramid.events import subscriber return subscriber(*ifaces) def test_register(self): from zope.interface import Interface class IFoo(Interface): pass class IBar(Interface): pass dec = self._makeOne(IFoo, IBar) def foo(): pass config = DummyConfigurator() scanner = Dummy() scanner.config = config dec.register(scanner, None, foo) self.assertEqual(config.subscribed, [(foo, (IFoo, IBar))]) def test___call__(self): dec = self._makeOne() dummy_venusian = DummyVenusian() dec.venusian = dummy_venusian def foo(): pass dec(foo) self.assertEqual(dummy_venusian.attached, [(foo, dec.register, 'bfg')])
class ViewPageTests(unittest.TestCase): def setUp(self): self.session = _initTestingDB() self.config = Configurator() self.config.begin() def tearDown(self): self.session.remove() self.config.end() def _callFUT(self, request): from tutorial.views import view_page return view_page(request) def test_it(self): from tutorial.models import Page request = testing.DummyRequest() request.matchdict['pagename'] = 'IDoExist' page = Page('IDoExist', 'Hello CruelWorld IDoExist') self.session.add(page) _registerRoutes(self.config) info = self._callFUT(request) self.assertEqual(info['page'], page) self.assertEqual( info['content'], '<div class="document">\n' '<p>Hello <a href="http://example.com/add_page/CruelWorld">' 'CruelWorld</a> ' '<a href="http://example.com/IDoExist">' 'IDoExist</a>' '</p>\n</div>\n') self.assertEqual(info['edit_url'], 'http://example.com/IDoExist/edit_page')
def registerDummySecurityPolicy(userid=None, groupids=(), permissive=True): """ Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`authorization policy`. The behavior of the registered :term:`authorization policy` depends on the ``permissive`` argument. If ``permissive`` is true, a permissive :term:`authorization policy` is registered; this policy allows all access. If ``permissive`` is false, a nonpermissive :term:`authorization policy` is registered; this policy denies all access. The behavior of the registered :term:`authentication policy` depends on the values provided for the ``userid`` and ``groupids`` argument. The authentication policy will return the userid identifier implied by the ``userid`` argument and the group ids implied by the ``groupids`` argument when the :func:`pyramid.security.authenticated_userid` or :func:`pyramid.security.effective_principals` APIs are used. This function is most useful when testing code that uses the APIs named :func:`pyramid.security.has_permission`, :func:`pyramid.security.authenticated_userid`, :func:`pyramid.security.effective_principals`, and :func:`pyramid.security.principals_allowed_by_permission`. .. warning:: This API is deprecated as of :app:`Pyramid` 1.0. Instead use the :meth:`pyramid.configuration.Configurator.testing_securitypolicy` method in your unit and integration tests. """ registry = get_current_registry() config = Configurator(registry=registry) return config.testing_securitypolicy(userid=userid, groupids=groupids, permissive=permissive)
def renderer(_context, factory, name=''): # renderer factories must be registered eagerly so they can be # found by the view machinery reg = get_current_registry() config = Configurator(reg, package=_context.package) config.add_renderer(name, factory, _info=_context.info) _context.action(discriminator=(IRendererFactory, name))
def test_it_with_dotted_renderer(self): from zope.interface import implementedBy from pyramid.threadlocal import get_current_registry from pyramid.interfaces import IRequest from pyramid.interfaces import IView from pyramid.interfaces import IViewClassifier from pyramid.exceptions import Forbidden from pyramid.configuration import Configurator context = DummyContext() reg = get_current_registry() config = Configurator(reg) def dummy_renderer_factory(*arg, **kw): return lambda *arg, **kw: 'OK' config.add_renderer('.pt', dummy_renderer_factory) def view(request): return {} self._callFUT(context, view, renderer='fake.pt') actions = context.actions regadapt = actions[0] register = regadapt['callable'] register() derived_view = reg.adapters.lookup( (IViewClassifier, IRequest, implementedBy(Forbidden)), IView, default=None) self.assertNotEqual(derived_view, None) self.assertEqual(derived_view(None, None).body, 'OK') self.assertEqual(derived_view.__name__, 'bwcompat_view')
class AddPageTests(unittest.TestCase): def setUp(self): self.session = _initTestingDB() self.config = Configurator() self.config.begin() def tearDown(self): self.session.remove() self.config.end() def _callFUT(self, request): from tutorial.views import add_page return add_page(request) def test_it_notsubmitted(self): _registerRoutes(self.config) request = testing.DummyRequest() request.matchdict = {'pagename':'AnotherPage'} info = self._callFUT(request) self.assertEqual(info['page'].data,'') self.assertEqual(info['save_url'], 'http://example.com/add_page/AnotherPage') def test_it_submitted(self): from tutorial.models import Page _registerRoutes(self.config) request = testing.DummyRequest({'form.submitted':True, 'body':'Hello yo!'}) request.matchdict = {'pagename':'AnotherPage'} self._callFUT(request) page = self.session.query(Page).filter_by(name='AnotherPage').one() self.assertEqual(page.data, 'Hello yo!')
class TestGetSettings(unittest.TestCase): def setUp(self): from pyramid.configuration import Configurator from pyramid.registry import Registry registry = Registry('testing') self.config = Configurator(registry=registry) self.config.begin() from zope.deprecation import __show__ __show__.off() def tearDown(self): self.config.end() from zope.deprecation import __show__ __show__.on() def _callFUT(self): from pyramid.settings import get_settings return get_settings() def test_it_nosettings(self): self.assertEqual(self._callFUT(), None) def test_it_withsettings(self): settings = {'a':1} self.config.registry.settings = settings self.assertEqual(self._callFUT(), settings)
def default_permission(_context, name): """ Register a default permission name """ # the default permission must be registered eagerly so it can # be found by the view registration machinery reg = get_current_registry() config = Configurator(reg, package=_context.package) config.set_default_permission(name) _context.action(discriminator=IDefaultPermission)
def register(): try: reg = _context.registry except AttributeError: # pragma: no cover (b/c) reg = get_current_registry() config = Configurator(reg, package=_context.package) config.set_forbidden_view(view=view, attr=attr, renderer=renderer, wrapper=wrapper, _info=_context.info)
def aclauthorizationpolicy(_context): policy = ACLAuthorizationPolicy() # authorization policies must be registered eagerly so they can be # found by the view registration machinery reg = get_current_registry() config = Configurator(reg, package=_context.package) config._set_authorization_policy(policy, _info=_context.info) _context.action(discriminator=IAuthorizationPolicy)
def remoteuserauthenticationpolicy(_context, environ_key='REMOTE_USER', callback=None): policy = RemoteUserAuthenticationPolicy(environ_key=environ_key, callback=callback) # authentication policies must be registered eagerly so they can # be found by the view registration machinery reg = get_current_registry() config = Configurator(reg, package=_context.package) config._set_authentication_policy(policy, _info=_context.info) _context.action(discriminator=IAuthenticationPolicy)
def register(): config = Configurator(reg, package=_context.package) config.add_view( permission=permission, context=context, view=view, name=name, request_type=request_type, route_name=route_name, request_method=request_method, request_param=request_param, containment=containment, attr=attr, renderer=renderer, wrapper=wrapper, xhr=xhr, accept=accept, header=header, path_info=path_info, custom_predicates=custom_predicates, _info=_context.info)
def renderer(_context, factory, name=''): # renderer factories must be registered eagerly so they can be # found by the view machinery try: reg = _context.registry except AttributeError: # pragma: no cover (b/c) reg = get_current_registry() config = Configurator(reg, package=_context.package) config.add_renderer(name, factory, _info=_context.info) _context.action(discriminator=(IRendererFactory, name))
def repozewho1authenticationpolicy(_context, identifier_name='auth_tkt', callback=None): policy = RepozeWho1AuthenticationPolicy(identifier_name=identifier_name, callback=callback) # authentication policies must be registered eagerly so they can # be found by the view registration machinery reg = get_current_registry() config = Configurator(reg, package=_context.package) config._set_authentication_policy(policy, _info=_context.info) _context.action(discriminator=IAuthenticationPolicy)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(root_factory=get_root, settings=settings) config.begin() config.add_view('som.views.my_view', context='som.models.MyModel', renderer='som:templates/mytemplate.pt') config.add_static_view('static', 'som:static') config.end() return config.make_wsgi_app()
class Base(object): def setUp(self): from pyramid.configuration import Configurator self.config = Configurator() self.config.begin() import os here = os.path.abspath(os.path.dirname(__file__)) self.templates_dir = os.path.join(here, 'fixtures') def tearDown(self): self.config.end()
def default_permission(_context, name): """ Register a default permission name """ # the default permission must be registered eagerly so it can # be found by the view registration machinery try: reg = _context.registry except AttributeError: # pragma: no cover (b/c) reg = get_current_registry() config = Configurator(reg, package=_context.package) config.set_default_permission(name) _context.action(discriminator=IDefaultPermission)
def aclauthorizationpolicy(_context): policy = ACLAuthorizationPolicy() # authorization policies must be registered eagerly so they can be # found by the view registration machinery try: reg = _context.registry except AttributeError: # pragma: no cover (b/c) reg = get_current_registry() config = Configurator(reg, package=_context.package) config._set_authorization_policy(policy, _info=_context.info) _context.action(discriminator=IAuthorizationPolicy)
class BaseViewTests(unittest.TestCase): def setUp(self): config['io_device'] = {'class': MockDriver, 'kw':{}} self.config = Configurator() self.config.begin() registerSettings(io_dev='') self.front_page = get_root(None) def tearDown(self): self.config.end()
def test_scanned(self): from pyramid.interfaces import IRequest from pyramid.interfaces import IView from pyramid.interfaces import IViewClassifier from pyramid.configuration import Configurator from pyramid.tests import test_integration config = Configurator() config.scan(test_integration) reg = config.registry view = reg.adapters.lookup( (IViewClassifier, IRequest, INothing), IView, name='') self.assertEqual(view, wsgiapptest)
def __init__( self, registry=None, package=None, # Entity level services. filter_specification_factory=None, order_specification_factory=None, # Application level services. service=None, cql_filter_specification_visitor=None, sql_filter_specification_visitor=None, eval_filter_specification_visitor=None, cql_order_specification_visitor=None, sql_order_specification_visitor=None, eval_order_specification_visitor=None, url_converter=None, **kw): if package is None: package = caller_package() call_setup = registry is None if call_setup: # Need to initialize our registry here to call our setup_registry # with the given custom option values rather than from the base # class constructor. # FIXME: There is some code duplication with Pyramid here. name_resolver = DottedNameResolver(package) name_resolver = name_resolver package_name = name_resolver.get_package_name() registry = Registry(package_name) self.registry = registry PyramidConfigurator.__init__(self, registry=registry, package=package, **kw) # Set up configurator's load_zcml method. self.add_directive('load_zcml', load_zcml, action_wrap=False) if call_setup: self.setup_registry( filter_specification_factory=filter_specification_factory, order_specification_factory=order_specification_factory, service=service, cql_filter_specification_visitor= cql_filter_specification_visitor, sql_filter_specification_visitor= sql_filter_specification_visitor, eval_filter_specification_visitor= eval_filter_specification_visitor, cql_order_specification_visitor=cql_order_specification_visitor, sql_order_specification_visitor=sql_order_specification_visitor, eval_order_specification_visitor= eval_order_specification_visitor, url_converter=url_converter, **kw)
def __init__(self, registry=None, package=None, # Entity level services. filter_specification_factory=None, order_specification_factory=None, # Application level services. service=None, cql_filter_specification_visitor=None, sql_filter_specification_visitor=None, eval_filter_specification_visitor=None, cql_order_specification_visitor=None, sql_order_specification_visitor=None, eval_order_specification_visitor=None, url_converter=None, **kw ): if package is None: package = caller_package() call_setup = registry is None if call_setup: # Need to initialize our registry here to call our setup_registry # with the given custom option values rather than from the base # class constructor. # FIXME: There is some code duplication with Pyramid here. name_resolver = DottedNameResolver(package) name_resolver = name_resolver package_name = name_resolver.get_package_name() registry = Registry(package_name) self.registry = registry PyramidConfigurator.__init__(self, registry=registry, package=package, **kw) # Set up configurator's load_zcml method. self.add_directive('load_zcml', load_zcml, action_wrap=False) if call_setup: self.setup_registry( filter_specification_factory=filter_specification_factory, order_specification_factory=order_specification_factory, service=service, cql_filter_specification_visitor= cql_filter_specification_visitor, sql_filter_specification_visitor= sql_filter_specification_visitor, eval_filter_specification_visitor= eval_filter_specification_visitor, cql_order_specification_visitor= cql_order_specification_visitor, sql_order_specification_visitor= sql_order_specification_visitor, eval_order_specification_visitor= eval_order_specification_visitor, url_converter=url_converter, **kw)
def setup_registry(self, filter_specification_factory=None, order_specification_factory=None, service=None, cql_filter_specification_visitor=None, sql_filter_specification_visitor=None, eval_filter_specification_visitor=None, cql_order_specification_visitor=None, sql_order_specification_visitor=None, eval_order_specification_visitor=None, url_converter=None, **kw): # Set default values for options. if filter_specification_factory is None: filter_specification_factory = FilterSpecificationFactory() if order_specification_factory is None: order_specification_factory = OrderSpecificationFactory() if service is None: service = Service() if cql_filter_specification_visitor is None: cql_filter_specification_visitor = CqlFilterSpecificationVisitor if sql_filter_specification_visitor is None: sql_filter_specification_visitor = SqlFilterSpecificationVisitor if eval_filter_specification_visitor is None: eval_filter_specification_visitor = \ ObjectFilterSpecificationVisitor if cql_order_specification_visitor is None: cql_order_specification_visitor = CqlOrderSpecificationVisitor if sql_order_specification_visitor is None: sql_order_specification_visitor = SqlOrderSpecificationVisitor if eval_order_specification_visitor is None: eval_order_specification_visitor = ObjectOrderSpecificationVisitor if url_converter is None: url_converter = ResourceUrlConverter PyramidConfigurator.setup_registry(self, **kw) self.__setup_everest( filter_specification_factory=filter_specification_factory, order_specification_factory=order_specification_factory, service=service, cql_filter_specification_visitor= cql_filter_specification_visitor, sql_filter_specification_visitor= sql_filter_specification_visitor, eval_filter_specification_visitor= eval_filter_specification_visitor, cql_order_specification_visitor= cql_order_specification_visitor, sql_order_specification_visitor= sql_order_specification_visitor, eval_order_specification_visitor= eval_order_specification_visitor, url_converter=url_converter)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ zodb_uri = settings.get('zodb_uri') if zodb_uri is None: raise ValueError("No 'zodb_uri' in application configuration.") finder = PersistentApplicationFinder(zodb_uri, appmaker) def get_root(request): return finder(request.environ) config = Configurator(root_factory=get_root, settings=settings) config.load_zcml('configure.zcml') return config.make_wsgi_app()
def setUp(self): import sys import twill from pyramid.configuration import Configurator config = Configurator(root_factory=self.root_factory) config.load_zcml(self.config) twill.add_wsgi_intercept('localhost', 6543, config.make_wsgi_app) if sys.platform is 'win32': # pragma: no cover out = open('nul:', 'wb') else: out = open('/dev/null', 'wb') twill.set_output(out) testing.setUp(registry=config.registry)
class ViewTests(unittest.TestCase): def setUp(self): self.config = Configurator() self.config.begin() def tearDown(self): self.config.end() def test_my_view(self): from pyramidapp.views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['project'], 'pyramidapp')
def app(global_config, **settings): """ This function returns a WSGI application. It is usually called by the PasteDeploy framework during ``paster serve``. """ config = Configurator(root_factory=get_root, settings=settings) config.begin() config.add_view('myproject.views.my_view', context='myproject.models.MyModel', renderer='myproject:templates/mytemplate.pt') config.add_static_view('static', 'myproject:static') config.end() return config.make_wsgi_app()
class ViewTests(unittest.TestCase): def setUp(self): self.config = Configurator() self.config.begin() def tearDown(self): self.config.end() def test_my_view(self): from academe.views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info["project"], "academe")
class ViewTests(unittest.TestCase): def setUp(self): self.config = Configurator() self.config.begin() def tearDown(self): self.config.end() def test_my_view(self): from tutorial.views import my_view context = testing.DummyModel() request = testing.DummyRequest() info = my_view(context, request) self.assertEqual(info['project'], 'tutorial')
def setup_registry(self, filter_specification_factory=None, order_specification_factory=None, service=None, cql_filter_specification_visitor=None, sql_filter_specification_visitor=None, eval_filter_specification_visitor=None, cql_order_specification_visitor=None, sql_order_specification_visitor=None, eval_order_specification_visitor=None, url_converter=None, **kw): # Set default values for options. if filter_specification_factory is None: filter_specification_factory = FilterSpecificationFactory() if order_specification_factory is None: order_specification_factory = OrderSpecificationFactory() if service is None: service = Service() if cql_filter_specification_visitor is None: cql_filter_specification_visitor = CqlFilterSpecificationVisitor if sql_filter_specification_visitor is None: sql_filter_specification_visitor = SqlFilterSpecificationVisitor if eval_filter_specification_visitor is None: eval_filter_specification_visitor = \ ObjectFilterSpecificationVisitor if cql_order_specification_visitor is None: cql_order_specification_visitor = CqlOrderSpecificationVisitor if sql_order_specification_visitor is None: sql_order_specification_visitor = SqlOrderSpecificationVisitor if eval_order_specification_visitor is None: eval_order_specification_visitor = ObjectOrderSpecificationVisitor if url_converter is None: url_converter = ResourceUrlConverter PyramidConfigurator.setup_registry(self, **kw) self.__setup_everest( filter_specification_factory=filter_specification_factory, order_specification_factory=order_specification_factory, service=service, cql_filter_specification_visitor=cql_filter_specification_visitor, sql_filter_specification_visitor=sql_filter_specification_visitor, eval_filter_specification_visitor=eval_filter_specification_visitor, cql_order_specification_visitor=cql_order_specification_visitor, sql_order_specification_visitor=sql_order_specification_visitor, eval_order_specification_visitor=eval_order_specification_visitor, url_converter=url_converter)
def main(global_config, **settings): config = Configurator(settings=settings) # Maintenance config.add_route('blitz-io-verification', '/mu-1e32b3b5-6f6be39c-4bc74834-6b7586e8') config.add_route('maintenance-200', '/maintenance/200') # Internal config.add_route('saasy-subscriptions', '/services/saasy/subscriptions') # API routing config = v_0_1_routing(config) config = v_0_2_routing(config) config.scan('tickee_api.resources') # OAuth 2 routing configure_oauth2_routing(config) config.scan('pyramid_oauth2.views') return config.make_wsgi_app()
def _makeOne(self, *arg, **kw): from pyramid.configuration import Configurator return Configurator(*arg, **kw)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ import logging logging.basicConfig(level=logging.DEBUG) config = Configurator(root_factory=get_root, settings=settings) config.begin() from pyramid_jinja2 import renderer_factory config.add_renderer('.jinja2', renderer_factory) # configure views, templates configure(config) # configure session import pyramid_beaker session_factory = pyramid_beaker.session_factory_from_settings(settings) config.set_session_factory(session_factory) # configure OpenID-specific storage import stucco_openid.models from openid.store import filestore stucco_openid.models.root.store = \ filestore.FileOpenIDStore(settings['openid.store_file_path']) config.end() return config.make_wsgi_app()
try: form.validate(request) except formish.FormError, e: log.debug(e) except Exception, e: log.debug(e) return {'form':form, 'form2':form} def goodbye_world(request): return Response('Goodbye world!') class QuietHandler(simple_server.WSGIRequestHandler): def log_message(self, format, *args): pass if __name__ == '__main__': import logging logging.basicConfig(level=logging.DEBUG) config = Configurator(settings={'reload_templates':True}) config.begin() sm = zope.component.getSiteManager() sm.registerUtility([resource_filename('pyramid_uniform', 'templates/zpt')], pyramid_formish.IFormishSearchPath) config.add_static_view('static', 'pyramid_uniform:templates/static') config.add_view(sample_form, renderer="pyramid_uniform:templates/index.pt") config.end() app = config.make_wsgi_app() simple_server.make_server('', 9876, app, handler_class=QuietHandler).serve_forever()
import json as simplejson from pyramid.configuration import Configurator from paste.httpserver import serve from beaker.cache import cache_regions, cache_region cache_regions['short_term'] = dict(type='memory', expire=30*60) def index(request): fml_endpoint = 'http://graph.facebook.com/search?q="so%20starving&type=post' @cache_region('short_term') def fb_data(key=None): fb_response = urllib.urlopen(key,).read() return simplejson.loads(fb_response)["data"] return {'data': fb_data(fml_endpoint)} settings = {} settings['mako.directories'] = './templates' config = Configurator(settings=settings) config.begin() config.add_view(index, name='', renderer='index.mako') config.end() application = config.make_wsgi_app() if __name__ == '__main__': serve(application, host='0.0.0.0')