def __delitem__(self, item, flush=True): """Delete a value from the container using the key.""" if isinstance(item, string_types): item = self[item] if item.__parent_uri__ == self.__uri__: if isinstance(item, BaseContainer): for key in item.keys(): item.__delitem__(key, False) get_current_registry().notify( ptah.events.ContentDeletingEvent(item)) Session = ptah.get_session().object_session(item) if item in Session: try: Session.delete(item) if flush: Session.flush() except: pass return raise KeyError(item)
def notify_role_for_acceptance(user_id, requester, model): """Notify the given ``user_id`` on ``model`` that s/he has been assigned a role on said model and can now accept the role. """ accounts = get_current_registry().getUtility(IOpenstaxAccounts) settings = get_current_registry().settings base_url = settings['webview.url'] link = urlparse.urljoin(base_url, '/users/role-acceptance/{}' .format(model.id)) subject = 'Requesting action on OpenStax CNX content' body = '''\ Hello {name}, {requester} added you to content titled {title}. Please go to the following link to accept your roles and license: {link} Thank you from your friends at OpenStax CNX '''.format(name=user_id, requester=requester, title=model.metadata['title'], link=link) try: accounts.send_message(user_id, subject, body) except urllib2.HTTPError: # Can't send messages via accounts for some reason - should be async! logger.warning("Failed sending notification message to {}" .format(user_id)) pass
def test_settings(self): browser = self.login_testbrowser() ctrl = browser.getControl browser.getLink(u'Calendar').click() ctrl('Title').value = u'Calendar' ctrl(name=u'save').click() for c in range(6): browser.getLink(u'Calendar').click() browser.getLink(u'Event').click() ctrl('Title').value = u'Event %d' % c ctrl('Start').value = u'2112-08-23 20:00:00' ctrl(name=u'save').click() browser.open(self.BASE_URL) assert u"Event 5" not in browser.contents settings = get_current_registry().settings settings['kotti_calendar.upcoming_events_widget.events_count'] = u'nan' browser.open(self.BASE_URL) assert u"Event 5" not in browser.contents settings = get_current_registry().settings settings['kotti_calendar.upcoming_events_widget.events_count'] = u'7' browser.open(self.BASE_URL) assert u"Event 5" in browser.contents
def __delitem__(self, item, flush=True): """Delete a value from the container using the key.""" if isinstance(item, string_types): item = self[item] if item.__parent_uri__ == self.__uri__: if isinstance(item, BaseContainer): for key in item.keys(): item.__delitem__(key, False) get_current_registry().notify( ptah.events.ContentDeletingEvent(item)) name = item.__name__ if self._v_keys: self._v_keys.remove(name) if self._v_items and name in self._v_items: del self._v_items[name] if item in Session: try: Session.delete(item) if flush: Session.flush() except: pass return raise KeyError(item)
def update(self): result = {} text_analyzer = get_current_registry().getUtility( ITextAnalyzer, 'text_analyzer') amendment_viewer = get_current_registry().getUtility( IAmendmentViewer, 'amendment_viewer') souptextdiff, explanations = amendment_viewer.get_explanation_diff( self.context, self.request) amendment_viewer.add_details(explanations, self.context, self.request, souptextdiff, self.readonly_explanation_template) text_diff = text_analyzer.soup_to_text(souptextdiff) not_published_ideas = [i for i in self.context.get_used_ideas() \ if not('published' in i.state)] values = {'context': self.context, 'explanationtext': text_diff, 'ideas': not_published_ideas} body = self.content(result=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates:[item]} return result
def __acl__(self): acl = self.admins() + self.viewers() + self.editors() + [DENY_ALL] get_current_registry().notify(ACLRequest(acl, self.context)) return acl
def get_searchable_text(context, default): root = find_root(context) catalog = root.catalog registry = get_current_registry() discriminators = list(getattr(registry, 'searchable_text_discriminators', ())) results = set() registry = get_current_registry() for index in registry.catalog_indexhelper['searchable_text'].linked: if index not in catalog: #pragma: no coverage # In case a bad name was linked in searchable_text, no reason to die because of it. continue disc = catalog[index].discriminator if isinstance(disc, string_types): attr_discriminator = _AttrDiscriminator(disc) discriminators.append(attr_discriminator) else: discriminators.append(catalog[index].discriminator) for discriminator in discriminators: res = discriminator(context, default) if res is default: continue if not isinstance(res, string_types): res = str(res) res = res.strip() if res: results.add(res) text = " ".join(results) text = text.strip() return text and text or default
def test_settings(webtest, root): from kotti_calendar.resources import Calendar from kotti_calendar.resources import Event root['calendar'] = calendar = Calendar(title=u'Calendar') for c in range(6): calendar['event-%d' % c] = Event( title=u'Event %d' % c, start=datetime(2112, 8, 23, c, 0, 0)) transaction.commit() resp = webtest.get('/') assert u"Event 5" not in resp.body settings = get_current_registry().settings settings['kotti_calendar.upcoming_events_widget.events_count'] = u'nan' resp = webtest.get('/') assert u"Event 5" not in resp.body settings = get_current_registry().settings settings['kotti_calendar.upcoming_events_widget.events_count'] = u'7' resp = webtest.get('/') assert u"Event 5" in resp.body
def get_text_amendment_diff_submitted(amendment, request): text_analyzer = get_current_registry().getUtility( ITextAnalyzer, 'text_analyzer') amendment_viewer = get_current_registry().getUtility( IAmendmentViewer, 'amendment_viewer') souptextdiff, explanations = amendment_viewer.get_explanation_diff( amendment, request) amendment_viewer.add_details(explanations, amendment, request, souptextdiff) return explanations, text_analyzer.soup_to_text(souptextdiff)
def get_settings(): from kotti.resources import Settings session = DBSession() db_settings = session.query(Settings).order_by(desc(Settings.id)).first() if db_settings is not None: reg_settings = dict(get_current_registry().settings) reg_settings.update(db_settings.data) return reg_settings else: return get_current_registry().settings
def update(self, **data): if self.__type__: tinfo = self.__type__ for field in tinfo.fieldset.fields(): val = data.get(field.name, field.default) if val is not form.null: setattr(self, field.name, val) get_current_registry().notify( ptah.events.ContentModifiedEvent(self))
def uncheckedDatas_graph(request): session = request.dbsession viewArgos = Base.metadata.tables["VArgosData_With_EquipIndiv"] queryArgos = ( select([viewArgos.c["type"].label("type"), func.count("*").label("nb")]) .where(viewArgos.c["checked"] == 0) .group_by(viewArgos.c["type"]) ) viewGSM = Base.metadata.tables["VGSMData_With_EquipIndiv"] queryGSM = select([func.count("*").label("nb")]).where(viewGSM.c["checked"] == 0) queryRFID = select([func.count("*").label("nb")]).where(Rfid.checked == 0) data = [] session1 = threadlocal.get_current_registry().dbmaker() session2 = threadlocal.get_current_registry().dbmaker() session3 = threadlocal.get_current_registry().dbmaker() global graphDataDate global pendingSensorData d = datetime.datetime.now() - datetime.timedelta(days=1) if graphDataDate["pendingSensorData"] is None or graphDataDate["pendingSensorData"] < d: graphDataDate["pendingSensorData"] = datetime.datetime.now() argosData = session1.execute(queryArgos).fetchall() for row in argosData: curRow = OrderedDict(row) lab = curRow["type"].upper() if lab == "ARG": lab = "ARGOS" data.append({"value": curRow["nb"], "label": lab}) for row in session2.execute(queryGSM).fetchall(): curRow = OrderedDict(row) data.append({"value": curRow["nb"], "label": "GSM"}) for row in session3.execute(queryRFID).fetchall(): curRow = OrderedDict(row) data.append({"value": curRow["nb"], "label": "RFID"}) data.sort(key=itemgetter("label")) pendingSensorData = data else: print("unchecked data already fetched") session1.close() session2.close() session3.close() return pendingSensorData
def after_request(response): if flask.request.method == 'OPTIONS': return response if 200 <= response.status_code < 300: match = re.match(r'^store\.(\w+)_annotation$', flask.request.endpoint) if match: action = match.group(1) if action != 'delete': annotation = json.loads(response.data) event = events.AnnotatorStoreEvent(annotation, action) get_current_registry().notify(event) return response
def __setitem__(self, key, item): """Set a new item in the container.""" if not isinstance(item, BaseContent): raise ValueError("Content object is required") if item.__uri__ == self.__uri__: raise ValueError("Can't set to it self") parents = [p.__uri__ for p in load_parents(self)] if item.__uri__ in parents: raise TypeError("Can't itself to chidlren") if key in self.keys(): raise KeyError(key) if item.__parent_uri__ is None: event = ptah.events.ContentAddedEvent(item) else: event = ptah.events.ContentMovedEvent(item) item.__name__ = key item.__parent__ = self item.__parent_uri__ = self.__uri__ item.__path__ = '%s%s/'%(self.__path__, key) if item not in Session: Session.add(item) # temporary keys if not self._v_items: self._v_items = {key: item} else: self._v_items[key] = item if key not in self._v_keys: self._v_keys.append(key) # recursevly update children paths def update_path(container): path = container.__path__ for item in container.values(): item.__path__ = '%s%s/'%(path, item.__name__) if isinstance(item, BaseContainer): update_path(item) if isinstance(item, BaseContainer): update_path(item) get_current_registry().notify(event)
def uncheckedDatas_graph(request): session = request.dbsession viewArgos = Base.metadata.tables['VArgosData_With_EquipIndiv'] queryArgos= select([viewArgos.c['type'].label('type'),func.count('*').label('nb')] ).where(viewArgos.c['checked'] == 0 ).group_by(viewArgos.c['type']) viewGSM = Base.metadata.tables['VGSMData_With_EquipIndiv'] queryGSM= select([func.count('*').label('nb')] ).where(viewGSM.c['checked'] == 0) queryRFID = select([func.count('*').label('nb')] ).where(Rfid.checked == 0) data = [] session1 = threadlocal.get_current_registry().dbmaker() session2 = threadlocal.get_current_registry().dbmaker() session3 = threadlocal.get_current_registry().dbmaker() global graphDataDate global pendingSensorData d = datetime.datetime.now() - datetime.timedelta(days=1) if graphDataDate['pendingSensorData'] is None or graphDataDate['pendingSensorData'] < d : graphDataDate['pendingSensorData'] = datetime.datetime.now() argosData = session1.execute(queryArgos).fetchall() for row in argosData: curRow = OrderedDict(row) lab = curRow['type'].upper() if lab == 'ARG': lab = 'ARGOS' data.append({'value':curRow['nb'],'label':lab}) for row in session2.execute(queryGSM).fetchall() : curRow = OrderedDict(row) data.append({'value':curRow['nb'],'label':'GSM'}) for row in session3.execute(queryRFID).fetchall() : curRow = OrderedDict(row) data.append({'value':curRow['nb'],'label':'RFID'}) data.sort(key = itemgetter('label')) pendingSensorData = data session1.close() session2.close() session3.close() return pendingSensorData
def versioned(path): version = get_current_registry().settings['app_version'] entry_path = get_current_registry().settings['entry_path'] + '/' if version is not None: agnosticPath = make_agnostic(path) parsedURL = urlparse(agnosticPath) # we don't do version when behind pserve (at localhost) if 'localhost:' not in parsedURL.netloc: parts = parsedURL.path.split(entry_path, 1) if len(parts) > 1: parsedURL = parsedURL._replace(path=parts[0] + entry_path + version + '/' + parts[1]) agnosticPath = urlunparse(parsedURL) return agnosticPath else: return path
def unit(request): response = BaseFixture() response.setUp() response.request = testing.DummyRequest() response.config = testing.setUp(request=response.request) get_current_registry().settings[CONFIG_RESOURCES] = models get_current_registry().settings['sqlalchemy.url'] =\ TEST_DATABASE_CONNECTION_STRING def fin(): response.tearDown() testing.tearDown() request.addfinalizer(fin) return response
def service_entry(self): """Implement this as a property to have the context when looking for the value of the setting""" if self._service_entry is None: settings = get_current_registry().settings self._service_entry = settings.get('tokenserver.service_entry') return self._service_entry
def remember(request, principal, **kw): """ Return a sequence of header tuples (e.g. ``[('Set-Cookie', 'foo=abc')]``) suitable for 'remembering' a set of credentials implied by the data passed as ``principal`` and ``*kw`` using the current :term:`authentication policy`. Common usage might look like so within the body of a view function (``response`` is assumed to be a :term:`WebOb` -style :term:`response` object computed previously by the view code):: from pyramid.security import remember headers = remember(request, 'chrism', password='******', max_age='86400') response.headerlist.extend(headers) return response If no :term:`authentication policy` is in use, this function will always return an empty sequence. If used, the composition and meaning of ``**kw`` must be agreed upon by the calling code and the effective authentication policy.""" try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c policy = reg.queryUtility(IAuthenticationPolicy) if policy is None: return [] else: return policy.remember(request, principal, **kw)
def virtual_root(resource, request): """ Provided any :term:`resource` and a :term:`request` object, return the resource object representing the :term:`virtual root` of the current :term:`request`. Using a virtual root in a :term:`traversal` -based :app:`Pyramid` application permits rooting, for example, the resource at the traversal path ``/cms`` at ``http://example.com/`` instead of rooting it at ``http://example.com/cms/``. If the ``resource`` passed in is a context obtained via :term:`traversal`, and if the ``HTTP_X_VHM_ROOT`` key is in the WSGI environment, the value of this key will be treated as a 'virtual root path': the :func:`pyramid.traversal.find_resource` API will be used to find the virtual root resource using this path; if the resource is found, it will be returned. If the ``HTTP_X_VHM_ROOT`` key is not present in the WSGI environment, the physical :term:`root` of the resource tree will be returned instead. Virtual roots are not useful at all in applications that use :term:`URL dispatch`. Contexts obtained via URL dispatch don't really support being virtually rooted (each URL dispatch context is both its own physical and virtual root). However if this API is called with a ``resource`` argument which is a context obtained via URL dispatch, the resource passed in will be returned unconditionally.""" try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c urlgenerator = reg.queryMultiAdapter((resource, request), IContextURL) if urlgenerator is None: urlgenerator = TraversalContextURL(resource, request) return urlgenerator.virtual_root()
def get_text_amendment_diff(proposal, amendment): text_analyzer = get_current_registry().getUtility( ITextAnalyzer,'text_analyzer') soup, textdiff = text_analyzer.render_html_diff( getattr(proposal, 'text', ''), getattr(amendment, 'text', '')) return textdiff
def initialize_sql(engine, drop_all=False): DBSession.registry.clear() DBSession.configure(bind=engine) metadata.bind = engine if drop_all or os.environ.get('KOTTI_TEST_DB_STRING'): metadata.reflect() metadata.drop_all(engine) # Allow users of Kotti to cherry pick the tables that they want to use: settings = get_current_registry().settings tables = settings['kotti.use_tables'].strip() or None if tables: if 'settings' not in tables: tables += ' settings' tables = [metadata.tables[name] for name in tables.split()] if engine.dialect.name == 'mysql': # pragma: no cover from sqlalchemy.dialects.mysql.base import LONGBLOB File.__table__.c.data.type = LONGBLOB() metadata.create_all(engine, tables=tables) for populate in get_settings()['kotti.populators']: populate() commit() return DBSession()
def test_hide_capabilities_set_get_capabilities_request(self): request = Request.blank("/test?REQUEST=GetCapabilities") request.registry = get_current_registry() request.registry.settings = { "hide_capabilities": True } self.assertFalse(self.predicate(None, request))
def setUp(self): from pyramid.threadlocal import get_current_registry from kotti.url_normalizer import url_normalizer r = get_current_registry() settings = r.settings = {} settings['kotti.url_normalizer'] = [url_normalizer] settings['kotti.url_normalizer.map_non_ascii_characters'] = False
def load( self, directory, parent=None, subresources=True, verbose=False, dry_run=False, registry=None ): """ Load a dump of a resource and return the resource.""" if registry is None: registry = get_current_registry() self.set_yaml(registry) stack = [(self.ospath.abspath(self.ospath.normpath(directory)), parent)] first = None dumpers = self.get_dumpers(registry) while stack: # breadth-first is easiest directory, parent = stack.pop() context = self._make_load_context( directory, registry, dumpers, verbose, dry_run ) self.logger.info('Loading %s' % directory) resource = context.load(parent) if first is None: first = resource if not subresources: break subobjects_dir = self.ospath.join(directory, RESOURCES_DIRNAME) if self.ospath.exists(subobjects_dir): for fn in self.oslistdir(subobjects_dir): fullpath = self.ospath.join(subobjects_dir, fn) subresource_fn = self.ospath.join( fullpath, RESOURCE_FILENAME ) if ( self.ospath.isdir(fullpath) and self.ospath.exists(subresource_fn) ): stack.append((fullpath, resource)) callbacks = registry.pop('loader_callbacks', ()) for callback in callbacks: callback(first) return first
def test_hide_capabilities_set_no_request_param(self): request = Request.blank("/test") request.registry = get_current_registry() request.registry.settings = { "hide_capabilities": True } self.assertTrue(self.predicate(None, request))
def registerAdapter(impl, for_=Interface, provides=Interface, name=''): """ Register a ZCA adapter component. The ``impl`` argument specifies the implementation of the component (often a class). The ``for_`` argument implies the ``for`` interface type used for this registration; it is :class:`zope.interface.Interface` by default. If ``for`` is not a tuple or list, it will be converted to a one-tuple before being passed to underlying :meth:`pyramid.registry.registerAdapter` API. The ``provides`` argument specifies the ZCA 'provides' interface, :class:`zope.interface.Interface` by default. The ``name`` argument is the empty string by default; it implies the name under which the adapter is registered. See `The ZCA book <http://www.muthukadan.net/docs/zca.html>`_ for more information about ZCA adapters. """ reg = get_current_registry() if not isinstance(for_, (tuple, list)): for_ = (for_,) reg.registerAdapter(impl, for_, provides, name=name) return impl
def has_permission(permission, context, request): """ Provided a permission (a string or unicode object), a context (a :term:`resource` instance) and a request object, return an instance of :data:`pyramid.security.Allowed` if the permission is granted in this context to the user implied by the request. Return an instance of :mod:`pyramid.security.Denied` if this permission is not granted in this context to this user. This function delegates to the current authentication and authorization policies. Return :data:`pyramid.security.Allowed` unconditionally if no authentication policy has been configured in this application.""" try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c authn_policy = reg.queryUtility(IAuthenticationPolicy) if authn_policy is None: return Allowed('No authentication policy in use.') authz_policy = reg.queryUtility(IAuthorizationPolicy) if authz_policy is None: raise ValueError('Authentication policy registered without ' 'authorization policy') # should never happen principals = authn_policy.effective_principals(request) return authz_policy.permits(context, principals, permission)
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.unauthenticated_userid`, :func:`pyramid.security.effective_principals`, and :func:`pyramid.security.principals_allowed_by_permission`. """ registry = get_current_registry() config = Configurator(registry=registry) result = config.testing_securitypolicy(userid=userid, groupids=groupids, permissive=permissive) config.commit() return result
def view_execution_permitted(context, request, name=''): """ If the view specified by ``context`` and ``name`` is protected by a :term:`permission`, check the permission associated with the view using the effective authentication/authorization policies and the ``request``. Return a boolean result. If no :term:`authorization policy` is in effect, or if the view is not protected by a permission, return ``True``. If no view can view found, an exception will be raised. .. versionchanged:: 1.4a4 An exception is raised if no view is found. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c provides = [IViewClassifier] + map_(providedBy, (request, context)) view = reg.adapters.lookup(provides, ISecuredView, name=name) if view is None: view = reg.adapters.lookup(provides, IView, name=name) if view is None: raise TypeError('No registered view satisfies the constraints. ' 'It would not make sense to claim that this view ' '"is" or "is not" permitted.') return Allowed( 'Allowed: view name %r in context %r (no permission defined)' % (name, context)) return view.__permitted__(context, request)
def factory(self): if self.__factory is None: reg = get_current_registry() self.__factory = reg.queryUtility(self.__ifactory) return self.__factory
def get_settings(): return get_current_registry().settings
def is_propertied(resource, registry=None): if registry is None: registry = get_current_registry() sheets = registry.content.metadata(resource, 'propertysheets', None) return sheets is not None
def load(self): "Loads the data from this session from persistent storage" self.namespace = self.namespace_class(self.id, data_dir=self.data_dir, digest_filenames=False, **self.namespace_args) now = time.time() if self.use_cookies: self.request['set_cookie'] = True self.namespace.acquire_read_lock() timed_out = False try: self.clear() try: session_data = self.namespace['session'] if (session_data is not None and self.encrypt_key): session_data = self._decrypt_data(session_data) # Memcached always returns a key, its None when its not # present if session_data is None: session_data = { '_creation_time': now, '_accessed_time': now } self.is_new = True except (KeyError, TypeError): session_data = { '_creation_time': now, '_accessed_time': now } self.is_new = True if session_data is None or len(session_data) == 0: session_data = { '_creation_time': now, '_accessed_time': now } self.is_new = True if self.timeout is not None and \ now - session_data['_accessed_time'] > self.timeout: try: user = dict({'username':session_data['auth.userid']}) setattr(self.request_object, 'user', user) get_current_registry().notify(ExpiredSessionEvent( self.request_object)) except (KeyError, TypeError): pass timed_out = True else: # Properly set the last_accessed time, which is different # than the *currently* _accessed_time if self.is_new or '_accessed_time' not in session_data: self.last_accessed = None else: self.last_accessed = session_data['_accessed_time'] # Update the current _accessed_time session_data['_accessed_time'] = now # Set the path if applicable if '_path' in session_data: self._path = session_data['_path'] self.update(session_data) self.accessed_dict = session_data.copy() finally: self.namespace.release_read_lock() if timed_out: self.invalidate()
def initialize(self): """Initialize the self.origins list.""" if self.origins is None: settings = get_current_registry().settings self.origins = settings.get(self.name, 'localhost').split(',')
def remove(self, name, send_events=True, moving=None, loading=False, registry=None): """ Same thing as ``__delitem__``. If ``send_events`` is false, suppress the sending of folder events. If ``moving`` is not ``None``, the ``moving`` argument must be the folder to which the named object will be moving. This value will be passed along as the ``moving`` attribute of the events sent as the result of this action. If ``loading`` is ``True``, the ``loading`` attribute of events sent as a result of calling this method will be ``True`` too. """ name = u(name) other = self.data[name] oid = get_oid(other, None) if registry is None: registry = get_current_registry() with statsd_timer('folder.remove'): if send_events: event = ObjectWillBeRemoved(other, self, name, moving=moving, loading=loading) self._notify(event, registry) if hasattr(other, '__parent__'): del other.__parent__ if hasattr(other, '__name__'): del other.__name__ del self.data[name] self._num_objects.change(-1) if self._order is not None: assert (len(self._order) == len(self._order_oids)) idx = self._order.index(name) order = list(self._order) order.pop(idx) order_oids = list(self._order_oids) order_oids.pop(idx) self._order = tuple(order) self._order_oids = tuple(order_oids) objectmap = find_objectmap(self) removed_oids = set([oid]) if objectmap is not None and oid is not None: removed_oids = objectmap.remove(oid, moving=moving is not None) if send_events: event = ObjectRemoved(other, self, name, removed_oids, moving=moving, loading=loading) self._notify(event, registry) return other
def _get_registry(self): if self._registry is None: return get_current_registry() return self._registry
def _registerImpl(self, impl): from pyramid.threadlocal import get_current_registry registry = get_current_registry() from pyramid.interfaces import ILocaleNegotiator registry.registerUtility(impl, ILocaleNegotiator)
def get_secret(): settings = get_current_registry().settings return settings['auth.secret']
def test_get_patterns(self): # patterns should have been populated patterns = get_current_registry()['endpoints_patterns'] self.assertDictEqual(patterns, {'sync-1.1': '{node}/1.1/{uid}'})
def _registerTraverser(self, traverser): from pyramid.threadlocal import get_current_registry reg = get_current_registry() from pyramid.interfaces import ITraverser from zope.interface import Interface reg.registerAdapter(traverser, (Interface, ), ITraverser)
def set_up(self): testing_set_up() reg = self._registry = get_current_registry() self._config = Configurator(registry=reg, package=package) self._config.setup_registry()
def save(self, update): settings = get_current_registry().settings update = update['local_file'] if update[ 'local_file'] is not None else update['remote_file'] sequence = re.match(BASE_UPDATE_PATTERN, update['filename']).group(1) logger.debug("forms.py ::: UpdateForm - sequence = %s" % sequence) # Updates directory: /opt/gecoscc/updates/<sequence> updatesdir = settings['updates.dir'] + sequence logger.debug("forms.py ::: UpdateForm - updatesdir = %s" % updatesdir) # Update zip file zipped = settings['updates.tmp'] + update['filename'] logger.debug("forms.py ::: UpdateForm - zipped = %s" % zipped) try: # https://docs.python.org/2/library/shutil.html # The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories # Checking copytree NFS shutil.copytree(update['decompress'], updatesdir) shutil.rmtree(update['decompress']) # Move zip file to updates dir shutil.move(zipped, updatesdir) # Decompress cookbook zipfile cookbookdir = settings['updates.cookbook'].format(sequence) logger.debug("forms.py ::: UpdateForm - cookbookdir = %s" % cookbookdir) for cookbook in os.listdir(cookbookdir): cookbook = cookbookdir + os.sep + cookbook logger.debug("forms.py ::: UpdateForm - cookbook = %s" % cookbook) if zipfile.is_zipfile(cookbook): zip_ref = zipfile.ZipFile(cookbook, 'r') zip_ref.extractall(cookbookdir + os.sep + settings['chef.cookbook_name']) zip_ref.close() # Insert update register self.request.db.updates.insert_one({ '_id': sequence, 'name': update['filename'], 'path': updatesdir, 'timestamp': int(time.time()), 'rollback': 0, 'user': self.request.user['username'] }) # Launching task for script execution script_runner.delay(self.request.user, sequence) link = '<a href="' + self.request.route_url( 'updates_tail', sequence=sequence) + '">' + _("here") + '</a>' self.created_msg(_("Update log. %s") % link) except OSError as e: if e.errno == errno.EACCES: self.created_msg( _('Permission denied: %s') % updatesdir, 'danger') else: self.created_msg( _('There was an error attempting to upload an update. Please contact an administrator' ), 'danger') logger.error("forms.py ::: UpdateForm - - " + \ "error saving update: %s"%(str(e))) logger.error("Traceback: %s" % (traceback.format_exc())) except (IOError, os.error) as e: logger.error("forms.py ::: UpdateForm - - " + \ "error saving update: %s"%(str(e))) logger.error("Traceback: %s" % (traceback.format_exc())) except errors.DuplicateKeyError as e: logger.error('Duplicate key error') self.created_msg( _('There was an error attempting to upload an update. Please contact an administrator' ), 'danger')
def add(self, name, other, send_events=True, reserved_names=(), duplicating=None, moving=None, loading=False, registry=None): """ Same as ``__setitem__``. If ``send_events`` is False, suppress the sending of folder events. Don't allow names in the ``reserved_names`` sequence to be added. If ``duplicating`` not ``None``, it must be the object which is being duplicated; a result of a non-``None`` duplicating means that oids will be replaced in objectmap. If ``moving`` is not ``None``, it must be the folder from which the object is moving; this will be the ``moving`` attribute of events sent by this function too. If ``loading`` is ``True``, the ``loading`` attribute of events sent as a result of calling this method will be ``True`` too. This method returns the name used to place the subobject in the folder (a derivation of ``name``, usually the result of ``self.check_name(name)``). """ if registry is None: registry = get_current_registry() name = self.check_name(name, reserved_names) if getattr(other, '__parent__', None): raise ValueError( 'obj %s added to folder %s already has a __parent__ attribute, ' 'please remove it completely from its existing parent (%s) ' 'before trying to readd it to this one' % (other, self, self.__parent__)) with statsd_timer('folder.add'): objectmap = find_objectmap(self) if objectmap is not None: basepath = resource_path_tuple(self) for node in postorder(other): node_path = node_path_tuple(node) path_tuple = basepath + (name, ) + node_path[1:] # the below gives node an objectid; if the will-be-added # event is the result of a duplication, replace the oid of # the node with a new one objectmap.add( node, path_tuple, duplicating=duplicating is not None, moving=moving is not None, ) if send_events: event = ObjectWillBeAdded( other, self, name, duplicating=duplicating, moving=moving, loading=loading, ) self._notify(event, registry) other.__parent__ = self other.__name__ = name self.data[name] = other self._num_objects.change(1) if self._order is not None: oid = get_oid(other) self._order += (name, ) self._order_oids += (oid, ) if send_events: event = ObjectAdded( other, self, name, duplicating=duplicating, moving=moving, loading=loading, ) self._notify(event, registry) return name
def resource_url(self, resource, *elements, **kw): """ Generate a string representing the absolute URL of the :term:`resource` object based on the ``wsgi.url_scheme``, ``HTTP_HOST`` or ``SERVER_NAME`` in the request, plus any ``SCRIPT_NAME``. The overall result of this method is always a UTF-8 encoded string. Examples:: request.resource_url(resource) => http://example.com/ request.resource_url(resource, 'a.html') => http://example.com/a.html request.resource_url(resource, 'a.html', query={'q':'1'}) => http://example.com/a.html?q=1 request.resource_url(resource, 'a.html', anchor='abc') => http://example.com/a.html#abc request.resource_url(resource, app_url='') => / Any positional arguments passed in as ``elements`` must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted. .. warning:: if no ``elements`` arguments are specified, the resource URL will end with a trailing slash. If any ``elements`` are used, the generated URL will *not* end in a trailing slash. If ``query`` is provided, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``query`` may be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of the :func:`pyramid.url.urlencode` function. This will produce a query string in the ``x-www-form-urlencoded`` format. A non-``x-www-form-urlencoded`` query string may be used by passing a *string* value as ``query`` in which case it will be URL-quoted (e.g. query="foo bar" will become "foo%20bar"). However, the result will not need to be in ``k=v`` form as required by ``x-www-form-urlencoded``. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``anchor`` is passed as ``foo`` and the resource URL is ``http://example.com/resource/url``, the resulting generated URL will be ``http://example.com/resource/url#foo``). .. note:: If ``anchor`` is passed as a string, it should be UTF-8 encoded. If ``anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. If both ``anchor`` and ``query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``scheme``, ``host``, or ``port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``http://foo.com/a``. If ``scheme`` is passed as ``https``, and an explicit ``port`` is not passed, the ``port`` value is assumed to have been passed as ``443``. Likewise, if ``scheme`` is passed as ``http`` and ``port`` is not passed, the ``port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``port`` whenever you pass ``scheme``. If a keyword argument ``app_url`` is passed and is not ``None``, it should be a string that will be used as the port/hostname/initial path portion of the generated URL instead of the default request application URL. For example, if ``app_url='http://foo'``, then the resulting url of a resource that has a path of ``/baz/bar`` will be ``http://foo/baz/bar``. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can pass ``app_url=''``. Passing ``app_url=''`` when the resource path is ``/baz/bar`` will return ``/baz/bar``. If ``app_url`` is passed and any of ``scheme``, ``port``, or ``host`` are also passed, ``app_url`` will take precedence and the values passed for ``scheme``, ``host``, and/or ``port`` will be ignored. If the ``resource`` passed in has a ``__resource_url__`` method, it will be used to generate the URL (scheme, host, port, path) for the base resource which is operated upon by this function. .. seealso:: See also :ref:`overriding_resource_url_generation`. If ``route_name`` is passed, this function will delegate its URL production to the ``route_url`` function. Calling ``resource_url(someresource, 'element1', 'element2', query={'a':1}, route_name='blogentry')`` is roughly equivalent to doing:: traversal_path = request.resource_path(someobject) url = request.route_url( 'blogentry', 'element1', 'element2', _query={'a':'1'}, traverse=traversal_path, ) It is only sensible to pass ``route_name`` if the route being named has a ``*remainder`` stararg value such as ``*traverse``. The remainder value will be ignored in the output otherwise. By default, the resource path value will be passed as the name ``traverse`` when ``route_url`` is called. You can influence this by passing a different ``route_remainder_name`` value if the route has a different ``*stararg`` value at its end. For example if the route pattern you want to replace has a ``*subpath`` stararg ala ``/foo*subpath``:: request.resource_url( resource, route_name='myroute', route_remainder_name='subpath' ) If ``route_name`` is passed, it is also permissible to pass ``route_kw``, which will passed as additional keyword arguments to ``route_url``. Saying ``resource_url(someresource, 'element1', 'element2', route_name='blogentry', route_kw={'id':'4'}, _query={'a':'1'})`` is roughly equivalent to:: traversal_path = request.resource_path_tuple(someobject) kw = {'id':'4', '_query':{'a':'1'}, 'traverse':traversal_path} url = request.route_url( 'blogentry', 'element1', 'element2', **kw, ) If ``route_kw`` or ``route_remainder_name`` is passed, but ``route_name`` is not passed, both ``route_kw`` and ``route_remainder_name`` will be ignored. If ``route_name`` is passed, the ``__resource_url__`` method of the resource passed is ignored unconditionally. This feature is incompatible with resources which generate their own URLs. .. note:: If the :term:`resource` used is the result of a :term:`traversal`, it must be :term:`location`-aware. The resource can also be the context of a :term:`URL dispatch`; contexts found this way do not need to be location-aware. .. note:: If a 'virtual root path' is present in the request environment (the value of the WSGI environ key ``HTTP_X_VHM_ROOT``), and the resource was obtained via :term:`traversal`, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL). .. note:: For backwards compatibility purposes, this method is also aliased as the ``model_url`` method of request. .. versionchanged:: 1.3 Added the ``app_url`` keyword argument. .. versionchanged:: 1.5 Allow the ``query`` option to be a string to enable alternative encodings. The ``anchor`` option will be escaped instead of using its raw string representation. Added the ``route_name``, ``route_kw``, and ``route_remainder_name`` keyword arguments. .. versionchanged:: 1.9 If ``query`` or ``anchor`` are falsey (such as ``None`` or an empty string) they will not be included in the generated url. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c url_adapter = reg.queryMultiAdapter((resource, self), IResourceURL) if url_adapter is None: url_adapter = ResourceURL(resource, self) virtual_path = getattr(url_adapter, 'virtual_path', None) urlkw = {} for name in ('app_url', 'scheme', 'host', 'port', 'query', 'anchor'): val = kw.get(name, None) if val is not None: urlkw['_' + name] = val if 'route_name' in kw: route_name = kw['route_name'] remainder = getattr(url_adapter, 'virtual_path_tuple', None) if remainder is None: # older user-supplied IResourceURL adapter without 1.5 # virtual_path_tuple remainder = tuple(url_adapter.virtual_path.split('/')) remainder_name = kw.get('route_remainder_name', 'traverse') urlkw[remainder_name] = remainder if 'route_kw' in kw: route_kw = kw.get('route_kw') if route_kw is not None: urlkw.update(route_kw) return self.route_url(route_name, *elements, **urlkw) app_url, qs, anchor = parse_url_overrides(self, urlkw) resource_url = None local_url = getattr(resource, '__resource_url__', None) if local_url is not None: # the resource handles its own url generation d = dict( virtual_path=virtual_path, physical_path=url_adapter.physical_path, app_url=app_url, ) # allow __resource_url__ to punt by returning None resource_url = local_url(self, d) if resource_url is None: # the resource did not handle its own url generation or the # __resource_url__ function returned None resource_url = app_url + virtual_path if elements: suffix = _join_elements(elements) else: suffix = '' return resource_url + suffix + qs + anchor
def _notify(self, event, registry=None): if registry is None: registry = get_current_registry() registry.subscribers((event, event.object, self), None)
def format_datetime(dt): """Format datetime into a human-readable format.""" registry = get_current_registry() timezone = pytz.timezone(registry.settings['app.timezone']) return dt.astimezone(timezone).strftime('%b %d, %Y at %H:%M:%S')
def invoke_exception_view(self, exc_info=None, request=None, secure=True, reraise=False): """ Executes an exception view related to the request it's called upon. The arguments it takes are these: ``exc_info`` If provided, should be a 3-tuple in the form provided by ``sys.exc_info()``. If not provided, ``sys.exc_info()`` will be called to obtain the current interpreter exception information. Default: ``None``. ``request`` If the request to be used is not the same one as the instance that this method is called upon, it may be passed here. Default: ``None``. ``secure`` If the exception view should not be rendered if the current user does not have the appropriate permission, this should be ``True``. Default: ``True``. ``reraise`` A boolean indicating whether the original error should be reraised if a :term:`response` object could not be created. If ``False`` then an :class:`pyramid.httpexceptions.HTTPNotFound`` exception will be raised. Default: ``False``. If a response is generated then ``request.exception`` and ``request.exc_info`` will be left at the values used to render the response. Otherwise the previous values for ``request.exception`` and ``request.exc_info`` will be restored. .. versionadded:: 1.7 .. versionchanged:: 1.9 The ``request.exception`` and ``request.exc_info`` properties will reflect the exception used to render the response where previously they were reset to the values prior to invoking the method. Also added the ``reraise`` argument. """ if request is None: request = self registry = getattr(request, 'registry', None) if registry is None: registry = get_current_registry() if registry is None: raise RuntimeError("Unable to retrieve registry") if exc_info is None: exc_info = sys.exc_info() exc = exc_info[1] attrs = request.__dict__ context_iface = providedBy(exc) # clear old generated request.response, if any; it may # have been mutated by the view, and its state is not # sane (e.g. caching headers) with hide_attrs(request, 'response', 'exc_info', 'exception'): attrs['exception'] = exc attrs['exc_info'] = exc_info # we use .get instead of .__getitem__ below due to # https://github.com/Pylons/pyramid/issues/700 request_iface = attrs.get('request_iface', IRequest) manager.push({'request': request, 'registry': registry}) try: response = _call_view( registry, request, exc, context_iface, '', view_types=None, view_classifier=IExceptionViewClassifier, secure=secure, request_iface=request_iface.combined, ) except Exception: if reraise: reraise_(*exc_info) raise finally: manager.pop() if response is None: if reraise: reraise_(*exc_info) raise HTTPNotFound # successful response, overwrite exception/exc_info attrs['exception'] = exc attrs['exc_info'] = exc_info return response
def include(config): stack.append(get_current_registry())
def route_url(self, route_name, *elements, **kw): """Generates a fully qualified URL for a named :app:`Pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Additional positional arguments (``*elements``) are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``{foo}/{bar}/*traverse``:: request.route_url('foobar', foo='1') => <KeyError exception> request.route_url('foobar', foo='1', bar='2') => <KeyError exception> request.route_url('foobar', foo='1', bar='2', traverse=('a','b')) => http://e.com/1/2/a/b request.route_url('foobar', foo='1', bar='2', traverse='/a/b') => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL after being URL-quoted-except-for-embedded-slashes. If ``_query`` is provided, it will be used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` may be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of the :func:`pyramid.url.urlencode` function. This will produce a query string in the ``x-www-form-urlencoded`` format. A non-``x-www-form-urlencoded`` query string may be used by passing a *string* value as ``_query`` in which case it will be URL-quoted (e.g. query="foo bar" will become "foo%20bar"). However, the result will not need to be in ``k=v`` form as required by ``x-www-form-urlencoded``. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be quoted per :rfc:`3986#section-3.5` and used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the route URL is ``http://example.com/route/url``, the resulting generated URL will be ``http://example.com/route/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If any of the keyword arguments ``_scheme``, ``_host``, or ``_port`` is passed and is non-``None``, the provided value will replace the named portion in the generated URL. For example, if you pass ``_host='foo.com'``, and the URL that would have been generated without the host replacement is ``http://example.com/a``, the result will be ``http://foo.com/a``. Note that if ``_scheme`` is passed as ``https``, and ``_port`` is not passed, the ``_port`` value is assumed to have been passed as ``443``. Likewise, if ``_scheme`` is passed as ``http`` and ``_port`` is not passed, the ``_port`` value is assumed to have been passed as ``80``. To avoid this behavior, always explicitly pass ``_port`` whenever you pass ``_scheme``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). If both ``_app_url`` and any of ``_scheme``, ``_host``, or ``_port`` are passed, ``_app_url`` takes precedence and any values passed for ``_scheme``, ``_host``, and ``_port`` will be ignored. This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments passed to this function might be augmented or changed. .. versionchanged:: 1.5 Allow the ``_query`` option to be a string to enable alternative encodings. The ``_anchor`` option will be escaped instead of using its raw string representation. .. versionchanged:: 1.9 If ``_query`` or ``_anchor`` are falsey (such as ``None`` or an empty string) they will not be included in the generated url. """ try: reg = self.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(self, elements, kw) app_url, qs, anchor = parse_url_overrides(self, kw) path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' return app_url + path + suffix + qs + anchor
def is_default_language(): request = get_current_request() settings = get_current_registry().settings return request.locale_name == settings.get('pyramid.default_locale_name')
def traverse(resource, path): """Given a resource object as ``resource`` and a string or tuple representing a path as ``path`` (such as the return value of :func:`pyramid.traversal.resource_path` or :func:`pyramid.traversal.resource_path_tuple` or the value of ``request.environ['PATH_INFO']``), return a dictionary with the keys ``context``, ``root``, ``view_name``, ``subpath``, ``traversed``, ``virtual_root``, and ``virtual_root_path``. A definition of each value in the returned dictionary: - ``context``: The :term:`context` (a :term:`resource` object) found via traversal or url dispatch. If the ``path`` passed in is the empty string, the value of the ``resource`` argument passed to this function is returned. - ``root``: The resource object at which :term:`traversal` begins. If the ``resource`` passed in was found via url dispatch or if the ``path`` passed in was relative (non-absolute), the value of the ``resource`` argument passed to this function is returned. - ``view_name``: The :term:`view name` found during :term:`traversal` or :term:`url dispatch`; if the ``resource`` was found via traversal, this is usually a representation of the path segment which directly follows the path to the ``context`` in the ``path``. The ``view_name`` will be a Unicode object or the empty string. The ``view_name`` will be the empty string if there is no element which follows the ``context`` path. An example: if the path passed is ``/foo/bar``, and a resource object is found at ``/foo`` (but not at ``/foo/bar``), the 'view name' will be ``u'bar'``. If the ``resource`` was found via urldispatch, the view_name will be the name the route found was registered with. - ``subpath``: For a ``resource`` found via :term:`traversal`, this is a sequence of path segments found in the ``path`` that follow the ``view_name`` (if any). Each of these items is a Unicode object. If no path segments follow the ``view_name``, the subpath will be the empty sequence. An example: if the path passed is ``/foo/bar/baz/buz``, and a resource object is found at ``/foo`` (but not ``/foo/bar``), the 'view name' will be ``u'bar'`` and the :term:`subpath` will be ``[u'baz', u'buz']``. For a ``resource`` found via url dispatch, the subpath will be a sequence of values discerned from ``*subpath`` in the route pattern matched or the empty sequence. - ``traversed``: The sequence of path elements traversed from the root to find the ``context`` object during :term:`traversal`. Each of these items is a Unicode object. If no path segments were traversed to find the ``context`` object (e.g. if the ``path`` provided is the empty string), the ``traversed`` value will be the empty sequence. If the ``resource`` is a resource found via :term:`url dispatch`, traversed will be None. - ``virtual_root``: A resource object representing the 'virtual' root of the resource tree being traversed during :term:`traversal`. See :ref:`vhosting_chapter` for a definition of the virtual root object. If no virtual hosting is in effect, and the ``path`` passed in was absolute, the ``virtual_root`` will be the *physical* root resource object (the object at which :term:`traversal` begins). If the ``resource`` passed in was found via :term:`URL dispatch` or if the ``path`` passed in was relative, the ``virtual_root`` will always equal the ``root`` object (the resource passed in). - ``virtual_root_path`` -- If :term:`traversal` was used to find the ``resource``, this will be the sequence of path elements traversed to find the ``virtual_root`` resource. Each of these items is a Unicode object. If no path segments were traversed to find the ``virtual_root`` resource (e.g. if virtual hosting is not in effect), the ``traversed`` value will be the empty list. If url dispatch was used to find the ``resource``, this will be ``None``. If the path cannot be resolved, a :exc:`KeyError` will be raised. Rules for passing a *string* as the ``path`` argument: if the first character in the path string is the with the ``/`` character, the path will considered absolute and the resource tree traversal will start at the root resource. If the first character of the path string is *not* the ``/`` character, the path is considered relative and resource tree traversal will begin at the resource object supplied to the function as the ``resource`` argument. If an empty string is passed as ``path``, the ``resource`` passed in will be returned. Resource path strings must be escaped in the following manner: each Unicode path segment must be encoded as UTF-8 and each path segment must escaped via Python's :mod:`urllib.quote`. For example, ``/path/to%20the/La%20Pe%C3%B1a`` (absolute) or ``to%20the/La%20Pe%C3%B1a`` (relative). The :func:`pyramid.traversal.resource_path` function generates strings which follow these rules (albeit only absolute ones). Rules for passing a *tuple* as the ``path`` argument: if the first element in the path tuple is the empty string (for example ``('', 'a', 'b', 'c')``, the path is considered absolute and the resource tree traversal will start at the resource tree root object. If the first element in the path tuple is not the empty string (for example ``('a', 'b', 'c')``), the path is considered relative and resource tree traversal will begin at the resource object supplied to the function as the ``resource`` argument. If an empty sequence is passed as ``path``, the ``resource`` passed in itself will be returned. No URL-quoting or UTF-8-encoding of individual path segments within the tuple is required (each segment may be any string or unicode object representing a resource name). Explanation of the conversion of ``path`` segment values to Unicode during traversal: Each segment is URL-unquoted, and decoded into Unicode. Each segment is assumed to be encoded using the UTF-8 encoding (or a subset, such as ASCII); a :exc:`pyramid.exceptions.URLDecodeError` is raised if a segment cannot be decoded. If a segment name is empty or if it is ``.``, it is ignored. If a segment name is ``..``, the previous segment is deleted, and the ``..`` is ignored. As a result of this process, the return values ``view_name``, each element in the ``subpath``, each element in ``traversed``, and each element in the ``virtual_root_path`` will be Unicode as opposed to a string, and will be URL-decoded. """ if is_nonstr_iter(path): # the traverser factory expects PATH_INFO to be a string, not # unicode and it expects path segments to be utf-8 and # urlencoded (it's the same traverser which accepts PATH_INFO # from user agents; user agents always send strings). if path: path = _join_path_tuple(tuple(path)) else: path = '' # The user is supposed to pass us a string object, never Unicode. In # practice, however, users indeed pass Unicode to this API. If they do # pass a Unicode object, its data *must* be entirely encodeable to ASCII, # so we encode it here as a convenience to the user and to prevent # second-order failures from cropping up (all failures will occur at this # step rather than later down the line as the result of calling # ``traversal_path``). path = ascii_native_(path) if path and path[0] == '/': resource = find_root(resource) reg = get_current_registry() request_factory = reg.queryUtility(IRequestFactory) if request_factory is None: from pyramid.request import Request # avoid circdep request_factory = Request request = request_factory.blank(path) request.registry = reg traverser = reg.queryAdapter(resource, ITraverser) if traverser is None: traverser = ResourceTreeTraverser(resource) return traverser(request)
def get_config(): """ Return the whole settings object. """ global _settings return _settings or get_current_registry().settings
def _get_overrides(self): reg = get_current_registry() overrides = reg.queryUtility(IPackageOverrides, self.module_name) return overrides
def registerSettings(**kw): registry = get_current_registry() from pyramid.interfaces import ISettings settings = DummySettings(**kw) registry.settings = settings registerUtility(settings, ISettings)
def _get_registry(request): try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c return reg
def get_roles_registry(registry=None): """ Get roles registry""" if registry is None: registry = get_current_registry() return registry._roles
def get_local_roles(context, registry=None): if registry is None: registry = get_current_registry() return registry.queryAdapter(context, IRoles)
def _registerOverrides(self, overrides, name='pyramid.tests'): from pyramid.interfaces import IPackageOverrides from pyramid.threadlocal import get_current_registry reg = get_current_registry() reg.registerUtility(overrides, IPackageOverrides, name=name)
def extract_graph_name(self): from pyramid.threadlocal import get_current_registry reg = get_current_registry() host = reg.settings['public_hostname'] return URIRef('http://%s/data/ExcerptGraph/%d' % (host, self.id))