예제 #1
0
 def _getFieldContext(self, uid):
     if uid is not None:
         rc = getToolByName(aq_inner(self.context), 'reference_catalog')
         return rc.lookupObject(uid)
     else:
         deprecated(FieldsView, missing_uid_deprecation)
         return aq_inner(self.context)
    def kssValidateMultilanguageField(self, fieldname, uid=None):
        '''Validate a given multilanguage field
        '''
        # validate the field, actually

        if uid is not None:
            rc = getToolByName(aq_inner(self.context), 'reference_catalog')
            instance = rc.lookupObject(uid)
        else:
            deprecated(ValidationView, missing_uid_deprecation)
            instance = aq_inner(self.context)

        field = instance.getField(fieldname)
        if field.type in SKIP_KSSVALIDATION_FIELDTYPES or \
           not IMultilanguageField.providedBy(field):
            return self.render()
        value = dict([(key[key.find('___') + 3:-3], value)
                      for key, value in self.request.form.items()
                      if key.startswith(fieldname)])
        error = field.validate(value, instance, {}, REQUEST=self.request)
        # XXX
        if isinstance(error, str):
            error = error.decode('utf', 'replace')
        # replace the error on the page
        self.getCommandSet('atvalidation').issueFieldError(fieldname, error)
        return self.render()
예제 #3
0
def load_auth():
    """Loads authentication backend"""
    auth_backend = 'airflow.api.auth.backend.default'
    try:
        auth_backend = conf.get("api", "auth_backend")
    except conf.AirflowConfigException:
        pass

    try:
        API_AUTH.api_auth = import_module(auth_backend)

        if hasattr(API_AUTH.api_auth, 'client_auth'):
            warnings.warn(
                'Auth backend %s should provide a CLIENT_AUTH (instead of client_auth)' % auth_backend,
                DeprecationWarning)
            API_AUTH.api_auth.CLIENT_AUTH = API_AUTH.api_auth.client_auth
        else:
            API_AUTH.api_auth.client_auth = deprecated(
                'use CLIENT_AUTH',
                API_AUTH.api_auth.CLIENT_AUTH
            )
    except ImportError as err:
        LOG.critical(
            "Cannot import %s for API authentication due to: %s",
            auth_backend, err
        )
        raise AirflowException(err)
예제 #4
0
def load_auth():
    """Loads authentication backend"""

    auth_backend = 'airflow.api.auth.backend.default'
    try:
        auth_backend = conf.get("api", "auth_backend")
    except AirflowConfigException:
        pass

    try:
        api_auth = import_module(auth_backend)

        if api_auth is not API_AUTH.api_auth:
            # Only warn about this if the setting has changed

            if hasattr(api_auth, 'client_auth'):
                warnings.warn(
                    'Auth backend %s should provide a CLIENT_AUTH (instead of client_auth)'
                    % auth_backend, DeprecationWarning)
                api_auth.CLIENT_AUTH = api_auth.client_auth
            else:
                api_auth.client_auth = deprecated('use CLIENT_AUTH',
                                                  api_auth.CLIENT_AUTH)
            API_AUTH.api_auth = api_auth
    except ImportError as err:
        log.critical("Cannot import %s for API authentication due to: %s",
                     auth_backend, err)
        raise AirflowException(err)
예제 #5
0
class Batch(QuantumBatch):

    b_start_str = 'b_start'

    def __init__(self,
                 sequence,
                 size,
                 start=0,
                 end=0,
                 orphan=0,
                 overlap=0,
                 pagerange=7,
                 quantumleap=0,
                 b_start_str='b_start'):
        super(Batch, self).__init__(sequence, size, start, end, orphan,
                                    overlap, pagerange, quantumleap)
        self.b_start_str = b_start_str

    def __len__(self):
        return self.length

    __len__ = deprecated(
        __len__,
        ('Using len() for getting the actual pagesize is deprecated. Use the '
         '`pagesize` attribute instead.'))

    def initialize(self, start, end, size):
        super(Batch, self).initialize(start, end, size)
        self.pagerange, self.pagerangestart, self.pagerangeend = \
            calculate_pagerange(self.pagenumber, self.numpages, self.pagerange)

    def pageurl(self, formvariables, pagenumber=-1):
        """ Makes the url for a given page """
        if pagenumber == -1:
            pagenumber = self.pagenumber
        b_start = pagenumber * (self.pagesize - self.overlap) - self.pagesize
        return make_query(formvariables, {self.b_start_str: b_start})

    def navurls(self, formvariables, navlist=None):
        """ Returns the page number and url for the navigation quick links """
        if navlist is None:
            navlist = []
        if not navlist:
            navlist = self.navlist
        return map(lambda x, formvariables=formvariables:
                   (x, self.pageurl(formvariables, x)),
                   navlist)

    def prevurls(self, formvariables):
        """ Helper method to get prev navigation list from templates """
        return self.navurls(formvariables, self.previous_pages)

    def nexturls(self, formvariables):
        """ Helper method to get next navigation list from templates """
        return self.navurls(formvariables, self.next_pages)

    prevlist = QuantumBatch.previous_pages
    nextlist = QuantumBatch.next_pages
예제 #6
0
def remember(request, userid=_marker, **kw):
    """
    Returns a sequence of header tuples (e.g. ``[('Set-Cookie', 'foo=abc')]``)
    on this request's response.
    These headers are suitable for 'remembering' a set of credentials
    implied by the data passed as ``userid`` 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):

    .. code-block:: python

       from pyramid.security import remember
       headers = remember(request, 'chrism', password='******', max_age='86400')
       response = request.response
       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.
    
    .. deprecated:: 1.6
        Renamed the ``principal`` argument to ``userid`` to clarify its
        purpose.
    """
    if userid is _marker:
        principal = kw.pop('principal', _marker)
        if principal is _marker:
            raise TypeError(
                'remember() missing 1 required positional argument: '
                '\'userid\'')
        else:
            deprecated(
                'principal',
                'The "principal" argument was deprecated in Pyramid 1.6. '
                'It will be removed in Pyramid 1.9. Use the "userid" '
                'argument instead.')
            userid = principal
    policy = _get_authentication_policy(request)
    if policy is None:
        return []
    return policy.remember(request, userid, **kw)
예제 #7
0
def remember(request, userid=_marker, **kw):
    """
    Returns a sequence of header tuples (e.g. ``[('Set-Cookie', 'foo=abc')]``)
    on this request's response.
    These headers are suitable for 'remembering' a set of credentials
    implied by the data passed as ``userid`` 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):

    .. code-block:: python

       from pyramid.security import remember
       headers = remember(request, 'chrism', password='******', max_age='86400')
       response = request.response
       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.
    
    .. deprecated:: 1.6
        Renamed the ``principal`` argument to ``userid`` to clarify its
        purpose.
    """
    if userid is _marker:
        principal = kw.pop('principal', _marker)
        if principal is _marker:
            raise TypeError(
                'remember() missing 1 required positional argument: '
                '\'userid\'')
        else:
            deprecated(
                'principal',
                'The "principal" argument was deprecated in Pyramid 1.6. '
                'It will be removed in Pyramid 1.9. Use the "userid" '
                'argument instead.')
            userid = principal
    policy = _get_authentication_policy(request)
    if policy is None:
        return []
    return policy.remember(request, userid, **kw)
예제 #8
0
class AuthenticationAPIMixin(object):
    @property
    def unauthenticated_userid(self):
        """
        .. deprecated:: 2.0

            ``unauthenticated_userid`` does not have an equivalent in the new
            security system.  Use :attr:`.authenticated_userid` or
            :attr:`.identity` instead.  See :ref:`upgrading_auth` for more
            information.

        Return an object which represents the *claimed* (not verified) user
        id of the credentials present in the request. ``None`` if there is no
        :term:`authentication policy` in effect or there is no user data
        associated with the current request.  This differs from
        :attr:`~pyramid.request.Request.authenticated_userid`, because the
        effective authentication policy will not ensure that a record
        associated with the userid exists in persistent storage.

        """
        authn = _get_authentication_policy(self)
        security = _get_security_policy(self)
        if authn is not None:
            return authn.unauthenticated_userid(self)
        elif security is not None:
            return str(security.identify(self))
        else:
            return None

    @property
    def effective_principals(self):
        """
        .. deprecated:: 2.0

            The new security policy has removed the concept of principals.  See
            :ref:`upgrading_auth` for more information.

        Return the list of 'effective' :term:`principal` identifiers
        for the ``request``. If no :term:`authentication policy` is in effect,
        this will return a one-element list containing the
        :data:`pyramid.security.Everyone` principal.

        """
        policy = _get_authentication_policy(self)
        if policy is None:
            return [Everyone]
        return policy.effective_principals(self)

    effective_principals = deprecated(
        effective_principals,
        'The new security policy has removed the concept of principals.  See '
        'https://docs.pylonsproject.org/projects/pyramid/en/latest'
        '/whatsnew-2.0.html#upgrading-authentication-authorization '
        'for more information.',
    )
예제 #9
0
def _integrate_plugins():
    """Integrate plugins to the context"""
    from airflow.plugins_manager import operators_modules
    for operators_module in operators_modules:
        sys.modules[operators_module.__name__] = operators_module
        globals()[operators_module._name] = operators_module

        ##########################################################
        # TODO FIXME Remove in Airflow 2.0

        if not os.environ.get('AIRFLOW_USE_NEW_IMPORTS', False):
            from zope.deprecation import deprecated
            for _operator in operators_module._objects:
                operator_name = _operator.__name__
                globals()[operator_name] = _operator
                deprecated(
                    operator_name,
                    "Importing plugin operator '{i}' directly from "
                    "'airflow.operators' has been deprecated. Please "
                    "import from 'airflow.operators.[plugin_module]' "
                    "instead. Support for direct imports will be dropped "
                    "entirely in Airflow 2.0.".format(i=operator_name))
예제 #10
0
    def kssValidateField(self, fieldname, value, uid=None):
        '''Validate a given field
        '''
        # validate the field, actually

        if uid is not None:
            rc = getToolByName(aq_inner(self.context), 'reference_catalog')
            instance = rc.lookupObject(uid)
        else:
            deprecated(ValidationView, missing_uid_deprecation)
            instance = aq_inner(self.context)

        field = instance.getField(fieldname)
        if field.type in SKIP_KSSVALIDATION_FIELDTYPES:
            return self.render()
        error = field.validate(value, instance, {})
        # XXX
        if isinstance(error, str):
            error = error.decode('utf', 'replace')
        # replace the error on the page
        self.getCommandSet('atvalidation').issueFieldError(fieldname, error, warning_only=False)
        return self.render()
예제 #11
0
def _integrate_plugins():
    """Integrate plugins to the context"""
    from airflow.plugins_manager import operators_modules
    for operators_module in operators_modules:
        sys.modules[operators_module.__name__] = operators_module
        globals()[operators_module._name] = operators_module

        ##########################################################
        # TODO FIXME Remove in Airflow 2.0

        if not os.environ.get('AIRFLOW_USE_NEW_IMPORTS', False):
            from zope.deprecation import deprecated
            for _operator in operators_module._objects:
                operator_name = _operator.__name__
                globals()[operator_name] = _operator
                deprecated(
                    operator_name,
                    "Importing plugin operator '{i}' directly from "
                    "'airflow.operators' has been deprecated. Please "
                    "import from 'airflow.operators.[plugin_module]' "
                    "instead. Support for direct imports will be dropped "
                    "entirely in Airflow 2.0.".format(i=operator_name))
예제 #12
0
def deprecate():
    """provide bbb for deprecations

    note: warnings are not printed unless it is enabled
    """
    from dexterity.membrane import behavior
    from dexterity.membrane.behavior import group
    from dexterity.membrane.behavior import user
    from dexterity.membrane.behavior import password

    behavior.membranegroup = deprecated(
        group,
        'module membranegroup is now named group.',
    )
    behavior.membraneuser = deprecated(
        user,
        'module membraneuser is now named user.',
    )
    behavior.membranepassword = deprecated(
        password,
        'module membranepassword is now named password.',
    )
예제 #13
0
def deprecate():
    """provide bbb for deprecations

    note: warnings are not printed unless it is enabled
    """
    from dexterity.membrane import behavior
    from dexterity.membrane.behavior import group
    from dexterity.membrane.behavior import user
    from dexterity.membrane.behavior import password

    behavior.membranegroup = deprecated(
        group,
        'module membranegroup is now named group.'
    )
    behavior.membraneuser = deprecated(
        user,
        'module membraneuser is now named user.'
    )
    behavior.membranepassword = deprecated(
        password,
        'module membranepassword is now named password.'
    )
    def kssValidateMultilanguageField(self, fieldname, uid=None):
        '''Validate a given multilanguage field
        '''
        # validate the field, actually

        if uid is not None:
            rc = getToolByName(aq_inner(self.context), 'reference_catalog')
            instance = rc.lookupObject(uid)
        else:
            deprecated(ValidationView, missing_uid_deprecation)
            instance = aq_inner(self.context)

        field = instance.getField(fieldname)
        if field.type in SKIP_KSSVALIDATION_FIELDTYPES or \
           not IMultilanguageField.providedBy(field):
            return self.render()
        value = dict([(key[key.find('___')+3:-3], value) for key, value in self.request.form.items() if key.startswith(fieldname)])
        error = field.validate(value, instance, {}, REQUEST=self.request)
        # XXX
        if isinstance(error, str):
            error = error.decode('utf', 'replace')
        # replace the error on the page
        self.getCommandSet('atvalidation').issueFieldError(fieldname, error)
        return self.render()
예제 #15
0
class LinkBase(object):
    def __call__(self, context, request):
        return TemplateStructure(
            render(
                self.template,
                dict(link=self, context=context, request=request),
                request,
            ))

    def selected(self, context, request):
        """ Returns True if the Link's url, based on its name,
        matches the request url

        If the link name is '', it will be selected for all urls ending in '/'
        """
        parsed = urlparse(unquote(request.url))

        # insert view markers @@ in last component of the path
        path = parsed.path.split('/')
        if '@@' not in path[-1]:
            path[-1] = '@@' + path[-1]
        path = '/'.join(path)
        url = urlunparse((parsed[0], parsed[1], path, '', '', ''))

        return url == self.url(context, request)

    def permitted(self, context, request):
        from kotti.security import view_permitted
        return view_permitted(context, request, self.name)

    def visible(self, context, request):
        permitted = self.permitted(context, request)
        if permitted:
            if self.predicate is not None:
                return self.predicate(context, request)
            else:
                return True
        return False

    @property
    def path(self):  # BBB
        return self.name

    path = deprecated(
        path,
        "The 'path' attribute has been deprecated as of Kotti 1.0.0.  Please "
        "use 'name' instead.",
    )
예제 #16
0
파일: util.py 프로젝트: xiang12383/Kotti
class LinkBase(object):
    def __call__(self, context, request):
        return TemplateStructure(
            render(
                self.template,
                dict(link=self, context=context, request=request),
                request,
                )
            )

    def selected(self, context, request):
        """ Returns True if the Link's url, based on its name,
        matches the request url

        If the link name is '', it will be selected for all urls ending in '/'
        """
        if request.view_name is not None:
            return request.view_name == self.name
        return False

    def permitted(self, context, request):
        from kotti.security import view_permitted
        return view_permitted(context, request, self.name)

    def visible(self, context, request):
        permitted = self.permitted(context, request)
        if permitted:
            if self.predicate is not None:
                return self.predicate(context, request)
            else:
                return True
        return False

    @property
    def path(self):  # BBB
        return self.name
    path = deprecated(
        path,
        "The 'path' attribute has been deprecated as of Kotti 1.0.0.  Please "
        "use 'name' instead.",
        )
예제 #17
0
    """
    A function that calls :meth:`pyramid.request.Request.has_permission`
    and returns its result.
    
    .. deprecated:: 1.5
        Use :meth:`pyramid.request.Request.has_permission` instead.

    .. versionchanged:: 1.5a3
        If context is None, then attempt to use the context attribute of self;
        if not set, then the AttributeError is propagated.
    """    
    return request.has_permission(permission, context)

deprecated(
    'has_permission',
    'As of Pyramid 1.5 the "pyramid.security.has_permission" API is now '
    'deprecated.  It will be removed in Pyramd 1.8.  Use the '
    '"has_permission" method of the Pyramid request instead.'
    )


def authenticated_userid(request):
    """
    A function that returns the value of the property
    :attr:`pyramid.request.Request.authenticated_userid`.
    
    .. deprecated:: 1.5
       Use :attr:`pyramid.request.Request.authenticated_userid` instead.
    """        
    return request.authenticated_userid

deprecated(
예제 #18
0
    item_id = getattr(obj, 'getId', None)
    if safe_callable(item_id):
        item_id = item_id()
    if item_id and not isIDAutoGenerated(context, item_id):
        return item_id
    if empty_value is _marker:
        empty_value = getEmptyTitle(context)
    return empty_value


def getSiteEncoding(context):
    return 'utf-8'


deprecated('getSiteEncoding',
           ('`getSiteEncoding` is deprecated. Plone only supports UTF-8 '
            'currently. This method always returns "utf-8"'))


# XXX portal_utf8 and utf8_portal probably can go away
def portal_utf8(context, str, errors='strict'):
    # Test
    unicode(str, 'utf-8', errors)
    return str


# XXX this is the same method as above
def utf8_portal(context, str, errors='strict'):
    # Test
    unicode(str, 'utf-8', errors)
    return str
예제 #19
0
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################

from zope.structuredtext.html import HTML as HTMLClass
from zope.deprecation import deprecated
deprecated(
    "HTMLClass",
    'The StructuredText package is deprecated and will be removed '
    'in Zope 2.12. Use zope.structuredtext.html.HTML instead.')
예제 #20
0
파일: session.py 프로젝트: Pylons/pyramid
    )

    return BaseCookieSessionFactory(
        signed_serializer,
        cookie_name=cookie_name,
        max_age=max_age,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
        timeout=timeout,
        reissue_time=reissue_time,
        set_on_exception=set_on_exception,
    )


check_csrf_origin = check_csrf_origin  # api
deprecated(
    'check_csrf_origin',
    'pyramid.session.check_csrf_origin is deprecated as of Pyramid '
    '1.9. Use pyramid.csrf.check_csrf_origin instead.',
)

check_csrf_token = check_csrf_token  # api
deprecated(
    'check_csrf_token',
    'pyramid.session.check_csrf_token is deprecated as of Pyramid '
    '1.9. Use pyramid.csrf.check_csrf_token instead.',
)
예제 #21
0
파일: util.py 프로젝트: disko/Kotti
    args = docopt(doc)
    # establish config file uri
    config_uri = args['<config_uri>']
    pyramid_env = bootstrap(config_uri)
    # Setup logging to allow log output from command methods
    setup_logging(config_uri)
    try:
        func(args)
    finally:
        pyramid_env['closer']()
    return 0


ViewLink = Link
deprecated(
    'ViewLink',
    "kotti.util.ViewLink has been renamed to Link as of Kotti 1.0.0."
    )


def _to_fieldstorage(fp, filename, mimetype, size, **_kwds):
    """ Build a :class:`cgi.FieldStorage` instance.

    Deform's :class:`FileUploadWidget` returns a dict, but
    :class:`depot.fields.sqlalchemy.UploadedFileField` likes
    :class:`cgi.FieldStorage` objects
    """
    f = cgi.FieldStorage()
    f.file = fp
    f.filename = filename
    f.type = mimetype
    f.length = size
예제 #22
0
def command(func, doc):
    args = docopt(doc)
    # establish config file uri
    config_uri = args['<config_uri>']
    pyramid_env = bootstrap(config_uri)
    # Setup logging to allow log output from command methods
    setup_logging(config_uri)
    try:
        func(args)
    finally:
        pyramid_env['closer']()
    return 0


ViewLink = Link
deprecated('ViewLink',
           "kotti.util.ViewLink has been renamed to Link as of Kotti 1.0.0.")


def _to_fieldstorage(fp, filename, mimetype, size, **_kwds):
    """ Build a :class:`cgi.FieldStorage` instance.

    Deform's :class:`FileUploadWidget` returns a dict, but
    :class:`depot.fields.sqlalchemy.UploadedFileField` likes
    :class:`cgi.FieldStorage` objects
    """
    f = cgi.FieldStorage()
    f.file = fp
    f.filename = filename
    f.type = mimetype
    f.length = size
    return f
예제 #23
0
from zope.interface import implementer


_marker = object()


@implementer(INameChooser)
@adapter(ILanguageRootFolder)
class LRFNameChooser(NormalizingNameChooser):
    """Special name chooser to fix issue where createContentInContainer is
    used to create a new content into LRF with an id, which exists already
    in the parent folder.

    """
    def chooseName(self, name, object):
        chosen = super(LRFNameChooser, self).chooseName(name, object)
        if chosen in self.context.objectIds():
            old_id = getattr(object, 'id', None)
            object.id = chosen
            chooser = ITranslationIdChooser(object)
            chosen = chooser(self.context, self.context.getId())
            object.id = old_id
        return chosen


@implementer(ILanguageRootFolder, INavigationRoot)
class LanguageRootFolder(Container):
    """Deprecated LanguageRootFolder custom base class"""
deprecated('LanguageRootFolder',
           'LanguageRootFolders should be migrate to DexterityContainers')
예제 #24
0
        args = ('provideAdapter',
                (for_, type), IDefaultViewName, '', name, _context.info)
        )

    _context.action(
        discriminator = None,
        callable = provideInterface,
        args = ('', type)
        )

    _context.action(
        discriminator = None,
        callable = provideInterface,
        args = ('', for_)
        )

from zope.deprecation import deprecated
deprecated('defaultView',
           'The zope:defaultView directive has been deprecated in favor of '
           'the browser:defaultView directive. '
           'Will be gone in Zope 3.3.')
############################################################################

def defaultLayer(_context, type, layer):
    import warnings
    warnings.warn("""The defaultLayer directive is deprecated and will
go away in Zope 3.4.  It doesn't actually do anything, and never did.

(%s)
""" % _context.info, DeprecationWarning)
예제 #25
0
        max_age=cookie_max_age,
        path=cookie_path,
        domain=cookie_domain,
        secure=cookie_secure,
        httponly=cookie_httponly,
        samesite=cookie_samesite,
        timeout=timeout,
        reissue_time=0,  # to keep session.accessed == session.renewed
        set_on_exception=cookie_on_exception,
    )


deprecated(
    'UnencryptedCookieSessionFactoryConfig',
    'The UnencryptedCookieSessionFactoryConfig callable is deprecated as of '
    'Pyramid 1.5.  Use ``pyramid.session.SignedCookieSessionFactory`` instead.'
    ' Caveat: Cookies generated using SignedCookieSessionFactory are not '
    'compatible with cookies generated using UnencryptedCookieSessionFactory, '
    'so existing user session data will be destroyed if you switch to it.')


def SignedCookieSessionFactory(
    secret,
    cookie_name='session',
    max_age=None,
    path='/',
    domain=None,
    secure=False,
    httponly=False,
    samesite='Lax',
    set_on_exception=True,
예제 #26
0
    'meta_type',
    'ModificationDate',
    'modified',
    'path',
    'portal_type',
    'review_state',
    'start',
    'Subject',
    'sync_uid',
    'Title',
    'total_comments'
    'UID',
]

_permissions = PERMISSIONS
deprecated('_permissions', 'Use PERMISSIONS variable instead.')


def _parseJSON(s):
    # XXX this should be changed to a try loads except return s
    if isinstance(s, six.string_types):
        s = s.strip()
        if (s.startswith('{') and s.endswith('}')) or \
                (s.startswith('[') and s.endswith(']')):  # detect if json
            return json_loads(s)
    return s


_unsafe_metadata = [
    'author_name',
    'commentors',
예제 #27
0
    def __init__(self,
                 connection_id=None,
                 hostname=None,
                 port=None,
                 virtual_host=None,
                 username=None,
                 password=None,
                 heartbeat=None,
                 prefetch_count=None,
                 tx_select=None):

        # Allow class variables to provide defaults for:

        # connection_id
        if self.connection_id is None and connection_id is None:
            connection_id =\
                getattr(self, 'grokcore.component.directive.name', 'default')
        if connection_id is not None:
            self.connection_id = connection_id

        # hostname
        if hostname is not None:
            self.hostname = hostname
        assert self.hostname is not None,\
            u"Connection configuration is missing hostname."

        # port
        if port is not None:
            self.port = port
        assert self.port is not None,\
            u"Connection configuration is missing port."

        # virtual_host
        if virtual_host is not None:
            self.virtual_host = virtual_host
        assert self.virtual_host is not None,\
            u"Connection configuration is missing virtual_host."

        # username
        if username is not None:
            self.username = username
        assert self.username is not None,\
            u"Connection configuration is missing username."

        # password
        if password is not None:
            self.password = password
        assert self.password is not None,\
            u"Connection configuration is missing password."

        # heartbeat
        if heartbeat is not None:
            self.heartbeat = heartbeat

        # prefetch_count
        if prefetch_count is not None:
            self.prefetch_count = prefetch_count

        # tx_select
        if tx_select is not None:
            self.tx_select = tx_select

        self._callbacks = CallbackManager()  # callbacks are NOT thread-safe
        self._reconnection_time = time.time()
        self._reconnection_delay = 1.0

        # BBB for affinitic.zamqp
        if getattr(self, 'userid', None):
            from zope.deprecation import deprecated
            self.username = self.userid
            self.userid =\
                deprecated(self.userid,
                           ('Connection.userid is no more. '
                            'Please, use Connection.username instead.'))

        logger.default(
            u"AMQP Broker connection '%s' created. "
            u"hostname: '%s', "
            u"port: '%s', "
            u"virtual_host: '%s', "
            u"username: '******', "
            u"heartbeat: '%s', "
            u"prefetch_count: '%s', "
            u"tx_select: '%s'", self.connection_id, self.hostname, self.port,
            self.virtual_host, self.username, self.heartbeat,
            self.prefetch_count, self.tx_select)
예제 #28
0
    )

    config.add_view(
        DocumentAddForm,
        name=Document.type_info.add_view,
        permission=Document.type_info.add_permission,
        renderer="kotti:templates/edit/node.pt",
    )

    config.add_view(FileEditForm, context=File, name="edit", permission="edit", renderer="kotti:templates/edit/node.pt")

    config.add_view(
        FileAddForm,
        name=File.type_info.add_view,
        permission=File.type_info.add_permission,
        renderer="kotti:templates/edit/node.pt",
    )


# DEPRECATED

from zope.deprecation import deprecated
from kotti_image.views.edit import ImageAddForm
from kotti_image.views.edit import ImageEditForm

__ = ImageAddForm, ImageEditForm  # pyflakes

deprecated(
    ("ImageAddForm", "ImageEditForm"), "Image was outfactored to the kotti_image package.  " "Please import from there."
)
예제 #29
0
def resource_url(resource, request, *elements, **kw):
    """
    This is a backwards compatibility function.  Its result is the same as
    calling::

        request.resource_url(resource, *elements, **kw)

    See :meth:`pyramid.request.Request.resource_url` for more information.
    """
    return request.resource_url(resource, *elements, **kw)

model_url = resource_url # b/w compat (forever)

deprecated(
    'model_url',
    'pyramid.url.model_url is deprecated as of Pyramid 1.0.  Use '
    '``pyramid.url.resource_url`` instead (API-compat, simple '
    'rename) or the ``pyramid.request.Request.resource_url`` method.')

def static_url(path, request, **kw):
    """
    This is a backwards compatibility function.  Its result is the same as
    calling::

        request.static_url(path, **kw)

    See :meth:`pyramid.request.Request.static_url` for more information.
    """
    return request.static_url(path, **kw)

def current_route_url(request, *elements, **kw):
예제 #30
0
        if local_url is not None:
            result = local_url(self.request, {"virtual_path": self.virtual_path, "physical_path": self.physical_path})
            if result is not None:
                # allow it to punt by returning ``None``
                return result

        app_url = self.request.application_url  # never ends in a slash
        return app_url + self.virtual_path


TraversalContextURL = ResourceURL  # deprecated as of 1.3

deprecated(
    "TraversalContextURL",
    'As of Pyramid 1.3 the, "pyramid.traversal.TraversalContextURL" class is '
    "scheduled to be removed.   Use the "
    '"pyramid.config.Configurator.add_resource_url_adapter" method to register '
    'a class that implements "pyramid.interfaces.IResourceURL" instead. '
    'See the "What\'s new In Pyramid 1.3" document for a further description.',
)


@lru_cache(1000)
def _join_path_tuple(tuple):
    return tuple and "/".join([quote_path_segment(x) for x in tuple]) or "/"


class DefaultRootFactory:
    __parent__ = None
    __name__ = None

    def __init__(self, request):
예제 #31
0
    A function that calls :meth:`pyramid.request.Request.has_permission`
    and returns its result.
    
    .. deprecated:: 1.5
        Use :meth:`pyramid.request.Request.has_permission` instead.

    .. versionchanged:: 1.5a3
        If context is None, then attempt to use the context attribute of self;
        if not set, then the AttributeError is propagated.
    """
    return request.has_permission(permission, context)


deprecated(
    'has_permission',
    'As of Pyramid 1.5 the "pyramid.security.has_permission" API is now '
    'deprecated.  It will be removed in Pyramid 1.8.  Use the '
    '"has_permission" method of the Pyramid request instead.')


def authenticated_userid(request):
    """
    A function that returns the value of the property
    :attr:`pyramid.request.Request.authenticated_userid`.
    
    .. deprecated:: 1.5
       Use :attr:`pyramid.request.Request.authenticated_userid` instead.
    """
    return request.authenticated_userid

예제 #32
0
        """Wether toolbar is visible or not in the actual context
        """

    def actions(category):
        """The filtered actions in the context. You can restrict the actions
        to just one category.
        """

    def portlet_assignable():
        """Whether or not the context is capable of having locally assigned
        portlets.
        """


class IViewView(Interface):
    """Marker interface which specifies that the current view is, in fact,
    a canonical "view" of the object, e.g. what may go on the "view" tab.
    """


class IPatternsSettingsRenderer(Interface):
    """ Interface for the adapter that renders the settings for patterns

    DEPRECATED
    """


IPatternsSettingsRenderer = deprecated(
    IPatternsSettingsRenderer,
    'This interface was deprecated because it was pointless.')
예제 #33
0
##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Utility Vocabulary.

This vocabulary provides terms for all utilities providing a given interface.

$Id: vocabulary.py 28582 2004-12-08 00:46:02Z srichter $
"""
from zope.deprecation import deprecated

from zope.app.component.vocabulary import *

deprecated(('UtilityTerm', 'UtilityVocabulary', 'UtilityNameTerm', 
            'UtilityComponentInterfacesVocabulary', 'UtilityNames'),
           'This class has been moved to zope.app.component.vocabulary. '
           'The reference will be gone in X3.3.')
           
예제 #34
0
    if is_image:
        return validate_image_data_mimetype


class AssetDataSchema(MappingSchema):
    """Data structure storing for the actual asset data."""

    data = FileStore(missing=required,
                     validator=deferred_validate_asset_mime_type)


asset_data_meta = sheet_meta._replace(
    isheet=IAssetData,
    schema_class=AssetDataSchema,
    readable=False,
)


class AssetFileDownload(Persistent):
    """Wrapper for a File object that allows downloading the asset data."""


deprecated('IAssetFileDownload', 'Use .resources.assets.AssetDownload instead')


def includeme(config):
    """Register sheets."""
    add_sheet_to_registry(has_asset_pool_meta, config.registry)
    add_sheet_to_registry(asset_metadata_meta, config.registry)
    add_sheet_to_registry(asset_data_meta, config.registry)
예제 #35
0
            if ldap_node.parent:
                ldap_node.parent._modified_children.add(ldap_node.name)

    @default
    def is_binary(self, name):
        return name in self.parent.root._binary_attributes

    @default
    def is_multivalued(self, name):
        return name in self.parent.root._multivalued_attributes


# B/C
AttributesBehavior = LDAPAttributesBehavior
deprecated('AttributesBehavior', """
``node.ext.ldap._node.AttributesBehavior`` is deprecated as of node.ext.ldap
1.0 and will be removed in node.ext.ldap 1.1. Use
``node.ext.ldap._node.LDAPAttributesBehavior`` instead.""")


@plumbing(
    LDAPAttributesBehavior,
    AttributesLifecycle)
class LDAPNodeAttributes(NodeAttributes):
    """Attributes for LDAPNode.
    """


@implementer(ILDAPStorage, IInvalidate)
class LDAPStorage(OdictStorage):
    attributes_factory = finalize(LDAPNodeAttributes)
예제 #36
0
파일: interfaces.py 프로젝트: AvdN/pyramid
        include: ``view`` (the view callable that returned the value),
        ``renderer_name`` (the template name or simple name of the
        renderer), ``context`` (the context object passed to the
        view), and ``request`` (the request object passed to the
        view)."""

class ITemplateRenderer(IRenderer):
    def implementation():
        """ Return the object that the underlying templating system
        uses to render the template; it is typically a callable that
        accepts arbitrary keyword arguments and returns a string or
        unicode object """

deprecated(
    'ITemplateRenderer',
    'As of Pyramid 1.5 the, "pyramid.interfaces.ITemplateRenderer" interface '
    'is scheduled to be removed. It was used by the Mako and Chameleon '
    'renderers which have been split into their own packages.'
    )

class IViewMapper(Interface):
    def __call__(self, object):
        """ Provided with an arbitrary object (a function, class, or
        instance), returns a callable with the call signature ``(context,
        request)``.  The callable returned should itself return a Response
        object.  An IViewMapper is returned by
        :class:`pyramid.interfaces.IViewMapperFactory`."""

class IViewMapperFactory(Interface):
    def __call__(self, **kw):
        """
        Return an object which implements
예제 #37
0
class static(static_view):
    """ Backwards compatibility alias for
    :class:`pyramid.static.static_view`; it overrides that class' constructor
    to pass ``use_subpath=True`` by default.  This class is deprecated as of
    :app:`Pyramid` 1.1.  Use :class:`pyramid.static.static_view` instead
    (probably with a ``use_subpath=True`` argument).
    """
    def __init__(self, root_dir, cache_max_age=3600, package_name=None):
        if package_name is None:
            package_name = caller_package().__name__
        static_view.__init__(self, root_dir, cache_max_age=cache_max_age,
                             package_name=package_name, use_subpath=True)

deprecated(
    'static',
    'The "pyramid.view.static" class is deprecated as of Pyramid 1.1; '
    'use the "pyramid.static.static_view" class instead with the '
    '"use_subpath" argument set to True.')

def render_view_to_response(context, request, name='', secure=True):
    """ Call the :term:`view callable` configured with a :term:`view
    configuration` that matches the :term:`view name` ``name``
    registered against the specified ``context`` and ``request`` and
    return a :term:`response` object.  This function will return
    ``None`` if a corresponding :term:`view callable` cannot be found
    (when no :term:`view configuration` matches the combination of
    ``name`` / ``context`` / and ``request``).

    If `secure`` is ``True``, and the :term:`view callable` found is
    protected by a permission, the permission will be checked before calling
    the view function.  If the permission check disallows view execution
예제 #38
0
파일: zcml.py 프로젝트: csenger/pyramid
    """ Given a ZCML filename as ``name`` and a Python package as
    ``package`` which the filename should be relative to, load the
    ZCML into the current ZCML registry.

    """
    registry = get_current_registry()
    configurator = Configurator(registry=registry, package=package)
    configurator.load_zcml(name)
    actions = configurator._ctx.actions[:]
    configurator.commit()
    return actions

file_configure = zcml_configure # backwards compat (>0.8.1)

deprecated(
    'zcml_configure',
    '(pyramid.zcml.zcml_configure is deprecated as of Pyramid 1.0.  Use'
    '``pyramid.config.Configurator.load_zcml`` instead.) ')

deprecated(
    'file_configure',
    '(pyramid.zcml.file_configure is deprecated as of Pyramid 1.0.  Use'
    '``pyramid.config.Configurator.load_zcml`` instead.) ')

def _rolledUpFactory(factories):
    def factory(ob):
        for f in factories:
            ob = f(ob)
        return ob
    # Store the original factory for documentation
    factory.factory = factories[0]
    return factory
    The object is a dictionary-like object that contains key/value pairs
    based on the dictionary passed as the ``settings`` argument to the
    :class:`pyramid.config.Configurator` constructor or the
    :func:`pyramid.router.make_app` API.

    .. warning:: This method is deprecated as of Pyramid 1.0.  Use
       ``pyramid.threadlocal.get_current_registry().settings`` instead or use
       the ``settings`` attribute of the registry available from the request
       (``request.registry.settings``).
    """
    reg = get_current_registry()
    return reg.settings

deprecated(
    'get_settings',
    '(pyramid.settings.get_settings is deprecated as of Pyramid 1.0.  Use'
    '``pyramid.threadlocal.get_current_registry().settings`` instead or use '
    'the ``settings`` attribute of the registry available from the request '
    '(``request.registry.settings``)).')

def asbool(s):
    """ Return the boolean value ``True`` if the case-lowered value of string
    input ``s`` is any of ``t``, ``true``, ``y``, ``on``, or ``1``, otherwise
    return the boolean value ``False``.  If ``s`` is the value ``None``,
    return ``False``.  If ``s`` is already one of the boolean values ``True``
    or ``False``, return it."""
    if s is None:
        return False
    if s in (True, False):
        return s
    s = str(s).strip()
    return s.lower() in ('t', 'true', 'y', 'yes', 'on', '1')
예제 #40
0
    """
    actions = []
    if hasattr(context, 'type_info'):
        actions = [a for a in context.type_info.action_links
                   if a.visible(context, request)]
    return {'actions': actions}


def includeme(config):
    """ Pyramid includeme hook.

    :param config: app config
    :type config: :class:`pyramid.config.Configurator`
    """

    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        config.scan(__name__)


# BBB starts here --- --- --- --- --- ---

render_tree_navigation = render_tree_navigation

deprecated(
    'render_tree_navigation',
    'render_tree_navigation has been moved to kotti.views.navigation as of '
    'Kotti 0.9.  Import from there instead.'
)
예제 #41
0
$Id: interfaces.py 40368 2005-11-25 15:09:45Z efge $
"""
__docformat__ = 'restructuredtext'

from zope.deprecation import deprecated

from zope.interface import Interface, Attribute, Invalid
from zope.component.interfaces import IView
from zope.interface.common.mapping import IItemMapping
from zope.interface.common.mapping import IReadMapping, IEnumerableMapping
from zope.app.location.interfaces import ILocation
from zope.app.event.interfaces import IObjectEvent
from zope.app.event.interfaces import IObjectModifiedEvent

deprecated('IContentContainer',
           'This interface has been deprecated. '
           'Check the "containerViews" zcml directive. '
           'The reference will be gone in 3.3')

class DuplicateIDError(KeyError):
    pass

class ContainerError(Exception):
    """An error of a container with one of its components."""

class InvalidContainerType(Invalid, TypeError):
    """The type of a container is not valid."""

class InvalidItemType(Invalid, TypeError):
    """The type of an item is not valid."""

class InvalidType(Invalid, TypeError):
예제 #42
0
파일: util.py 프로젝트: fschulze/Kotti
        request,
        item_mapping,
        item_to_children,
        )

# BBB starts here --- --- --- --- --- ---

appstruct = get_appstruct
BaseFormView = BaseFormView
AddFormView = AddFormView
EditFormView = EditFormView


deprecated(
    'appstruct',
    'appstruct is deprecated as of Kotti 0.6.2.  Use '
    '``kotti.views.form.get_appstruct`` instead.'
    )

deprecated(
    'get_appstruct',
    'get_appstruct is deprecated as of Kotti 0.6.3.  Use '
    '``kotti.views.form.get_appstruct`` instead.'
    )

deprecated(
    'disambiguate_name',
    'disambiguate_name is deprecated as of Kotti 0.6.2.  Use '
    '``kotti.util.disambiguate_name`` instead.'
    )
예제 #43
0
    # <__main__.Fudge object at 0x1cda890>
    # <object object at 0x7fa678f3e2a0> <object object at 0x7fa678f3e2a0>
    # <__main__.Another object at 0x1cda850>

    def virtual_root():
        """ Return the virtual root related to a request and the
        current context"""

    def __call__():
        """ Return a URL that points to the context. """


deprecated(
    'IContextURL',
    'As of Pyramid 1.3 the, "pyramid.interfaces.IContextURL" interface is '
    'scheduled to be removed.   Use the '
    '"pyramid.config.Configurator.add_resource_url_adapter" method to register '
    'a class that implements "pyramid.interfaces.IResourceURL" instead. '
    'See the "What\'s new In Pyramid 1.3" document for more details.')


class IPEP302Loader(Interface):
    """ See http://www.python.org/dev/peps/pep-0302/#id30.
    """
    def get_data(path):
        """ Retrieve data for and arbitrary "files" from storage backend.

        Raise IOError for not found.

        Data is returned as bytes.
        """
예제 #44
0
파일: testing.py 프로젝트: shazow/pyramid
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_securitypolicy`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_securitypolicy(userid=userid, groupids=groupids, permissive=permissive)
    config.commit()
    return result


deprecated(
    "registerDummySecurityPolicy",
    "The testing.registerDummySecurityPolicy API is deprecated as of "
    "Pyramid 1.0. Instead use the "
    "pyramid.config.Configurator.testing_securitypolicy "
    "method in your unit and integration tests.",
)


def registerResources(resources):
    """ Registers a dictionary of :term:`resource` objects that can be
    resolved via the :func:`pyramid.traversal.find_resource` API.

    The :func:`pyramid.traversal.find_resource` API is called with a
    path as one of its arguments.  If the dictionary you register when
    calling this method contains that path as a string key
    (e.g. ``/foo/bar`` or ``foo/bar``), the corresponding value will
    be returned to ``find_resource`` (and thus to your code) when
    :func:`pyramid.traversal.find_resource` is called with an
예제 #45
0
    :term:`Chameleon` ZPT template using the template implied by the
    ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.
    
    .. warning::

       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.get_renderer` instead.
    """
    package = caller_package()
    factory = renderers.RendererHelper(name=path, package=package)
    return factory.get_renderer()

deprecated(
    'get_renderer',
    '(pyramid.chameleon_zpt.get_renderer is deprecated '
    'as of Pyramid 1.0; instead use pyramid.renderers.get_renderer)')

def get_template(path):
    """ Return the underyling object representing a :term:`Chameleon`
    ZPT template using the template implied by the ``path`` argument.
    The ``path`` argument may be a package-relative path, an absolute
    path, or a :term:`asset specification`.

    .. warning::

       This API is deprecated in :app:`Pyramid` 1.0.  Use
       the ``implementation()`` method of a template renderer retrieved via
       :func:`pyramid.renderers.get_renderer` instead.
    """
    package = caller_package()
예제 #46
0
        context, request, **kwargs)


def add_renderer_globals(event):
    if event.get('renderer_name') != 'json':
        request = event['request']
        api = getattr(request, 'template_api', None)
        if api is None and request is not None:
            api = template_api(event['context'], event['request'])
        event['api'] = api


def is_root(context, request):
    return context is request.root
deprecated('is_root', "'is_root' is deprecated as of Kotti 1.0.0. "
           "Use the 'root_only=True' if you were using this as a "
           "'custom_predicates' predicate.")


class Slots(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __getattr__(self, name):
        for event_type in slot_events:
            if event_type.name == name:
                break
        else:
            raise AttributeError(name)
        value = []
예제 #47
0
if not os.path.isfile(WEBSERVER_CONFIG):
    log.info('Creating new FAB webserver config file in: %s', WEBSERVER_CONFIG)
    with open(WEBSERVER_CONFIG, 'w') as f:
        f.write(DEFAULT_WEBSERVER_CONFIG)

if conf.getboolean('core', 'unit_test_mode'):
    conf.load_test_config()

# Historical convenience functions to access config entries

load_test_config = conf.load_test_config
get = conf.get
getboolean = conf.getboolean
getfloat = conf.getfloat
getint = conf.getint
getsection = conf.getsection
has_option = conf.has_option
remove_option = conf.remove_option
as_dict = conf.as_dict
set = conf.set  # noqa

for func in [
        load_test_config, get, getboolean, getfloat, getint, has_option,
        remove_option, as_dict, set
]:
    deprecated(
        func, "Accessing configuration method '{f.__name__}' directly from "
        "the configuration module is deprecated. Please access the "
        "configuration from the 'configuration.conf' object via "
        "'conf.{f.__name__}'".format(f=func))
예제 #48
0
파일: url.py 프로젝트: cjw296/pyramid
        if isinstance(anchor, unicode):
            anchor = anchor.encode('utf-8')
        anchor = '#' + anchor

    if elements:
        suffix = _join_elements(elements)
    else:
        suffix = ''

    return resource_url + suffix + qs + anchor

model_url = resource_url # b/w compat (forever)

deprecated(
    'model_url',
    'pyramid.url.model_url is deprecated as of Pyramid 1.0.  Use'
    '``pyramid.url.resource_url`` instead (API-compat, simple '
    'rename).')

def static_url(path, request, **kw):
    """
    Generates a fully qualified URL for a static :term:`asset`.
    The asset must live within a location defined via the
    :meth:`pyramid.config.Configurator.add_static_view`
    :term:`configuration declaration` (see :ref:`static_assets_section`).

    .. note:: Calling :meth:`pyramid.Request.static_url` can be used to
              achieve the same result as :func:`pyramid.url.static_url`.

    Example::
예제 #49
0
    phash = text

    def __call__(self, context, request):
        req_principals = request.effective_principals
        if is_nonstr_iter(req_principals):
            rpset = set(req_principals)
            if self.val.issubset(rpset):
                return True
        return False


deprecated(
    'EffectivePrincipalsPredicate',
    'The new security policy has removed the concept of principals.  See '
    'https://docs.pylonsproject.org/projects/pyramid/en/latest'
    '/whatsnew-2.0.html#upgrading-authentication-authorization '
    'for more information.',
)


class Notted(object):
    def __init__(self, predicate):
        self.predicate = predicate

    def _notted_text(self, val):
        # if the underlying predicate doesnt return a value, it's not really
        # a predicate, it's just something pretending to be a predicate,
        # so dont update the hash
        if val:
            val = '!' + val
예제 #50
0
                {'virtual_path':self.virtual_path,
                 'physical_path':self.physical_path},
                )
            if result is not None:
                # allow it to punt by returning ``None``
                return result

        app_url = self.request.application_url # never ends in a slash
        return app_url + self.virtual_path

TraversalContextURL = ResourceURL # deprecated as of 1.3

deprecated(
    'TraversalContextURL',
    'As of Pyramid 1.3 the, "pyramid.traversal.TraversalContextURL" class is '
    'scheduled to be removed.   Use the '
    '"pyramid.config.Configurator.add_resource_url_adapter" method to register '
    'a class that implements "pyramid.interfaces.IResourceURL" instead. '
    'See the "What\'s new In Pyramid 1.3" document for a further description.'
    )

@lru_cache(1000)
def _join_path_tuple(tuple):
    return tuple and '/'.join([quote_path_segment(x) for x in tuple]) or '/'

class DefaultRootFactory:
    __parent__ = None
    __name__ = None
    def __init__(self, request):
        pass
예제 #51
0
class UpgradeInformationGatherer(object):
    adapts(ISetupTool)

    security = ClassSecurityInformation()

    def __init__(self, portal_setup):
        self.portal_setup = portal_setup
        self.portal = getToolByName(portal_setup,
                                    'portal_url').getPortalObject()
        self.cyclic_dependencies = False

    security.declarePrivate('get_profiles')

    def get_profiles(self, proposed_only=False, propose_deferrable=True):
        profiles = self._sort_profiles_by_dependencies(
            self._get_profiles(proposed_only=proposed_only,
                               propose_deferrable=propose_deferrable))
        profiles = flag_profiles_with_outdated_fs_version(profiles)
        profiles = extend_auto_upgrades_with_human_formatted_date_version(
            profiles)
        return profiles

    security.declarePrivate('get_upgrades')
    get_upgrades = deprecated(get_profiles,
                              'get_upgrades was renamed to get_profiles')

    security.declarePrivate('get_upgrades_by_api_ids')

    def get_upgrades_by_api_ids(self, *api_ids, **kwargs):
        propose_deferrable = kwargs.pop('propose_deferrable', True)
        upgrades = [
            upgrade for upgrade in reduce(
                list.__add__,
                map(itemgetter('upgrades'),
                    self.get_profiles(propose_deferrable=propose_deferrable)))
            if upgrade['api_id'] in api_ids
        ]

        missing_api_ids = (set(api_ids) -
                           set(map(itemgetter('api_id'), upgrades)))
        if missing_api_ids:
            raise UpgradeNotFound(tuple(missing_api_ids)[0])
        return upgrades

    security.declarePrivate('_get_profiles')

    def _get_profiles(self, proposed_only=False, propose_deferrable=True):
        for profileid in self.portal_setup.listProfilesWithUpgrades():
            if not self._is_profile_installed(profileid):
                continue

            data = self._get_profile_data(
                profileid,
                proposed_only=proposed_only,
                propose_deferrable=propose_deferrable)
            if len(data['upgrades']) == 0:
                continue

            if profileid == 'Products.CMFPlone:plone':
                # Plone has its own migration mechanism.
                # We do not support upgrading plone.
                continue

            yield data

    security.declarePrivate('_get_profile_data')

    def _get_profile_data(self,
                          profileid,
                          proposed_only=False,
                          propose_deferrable=True):
        db_version = self.portal_setup.getLastVersionForProfile(profileid)
        if isinstance(db_version, (tuple, list)):
            db_version = '.'.join(db_version)

        data = {
            'upgrades':
            self._get_profile_upgrades(profileid,
                                       proposed_only=proposed_only,
                                       propose_deferrable=propose_deferrable),
            'db_version':
            db_version
        }

        try:
            profile_info = self.portal_setup.getProfileInfo(profileid).copy()
            if 'for' in profile_info:
                del profile_info['for']
            data.update(profile_info)

        except KeyError as exc:
            if exc.args and exc.args[0] == profileid:
                # package was removed - profile is no longer available.
                return {'upgrades': []}

            else:
                raise

        return data

    security.declarePrivate('_get_profile_upgrades')

    def _get_profile_upgrades(self,
                              profileid,
                              proposed_only=False,
                              propose_deferrable=True):
        proposed_ids = set()
        upgrades = []

        proposed_upgrades = list(
            flatten_upgrades(self.portal_setup.listUpgrades(profileid)))
        all_upgrades = list(
            flatten_upgrades(
                self.portal_setup.listUpgrades(profileid, show_old=True)))

        for upgrade in proposed_upgrades:
            proposed_ids.add(upgrade['id'])

        for upgrade in all_upgrades:
            upgrade = upgrade.copy()
            if upgrade['id'] not in proposed_ids:
                upgrade['proposed'] = False
                upgrade['done'] = True

            if self._was_upgrade_executed(profileid, upgrade):
                upgrade['proposed'] = False
                upgrade['done'] = True

            upgrade['orphan'] = self._is_orphan(profileid, upgrade)
            if upgrade['orphan']:
                upgrade['proposed'] = True
                upgrade['done'] = False

            upgrade['deferrable'] = self._is_deferrable(upgrade)
            if upgrade['deferrable'] and upgrade['proposed']:
                upgrade['proposed'] = propose_deferrable

            if 'step' in upgrade:
                del upgrade['step']

            upgrade['profile'] = profileid
            upgrade['api_id'] = '@'.join((upgrade['sdest'], profileid))

            if proposed_only and not upgrade['proposed']:
                continue

            upgrades.append(upgrade)

        return upgrades

    security.declarePrivate('_is_profile_installed')

    def _is_profile_installed(self, profileid):
        try:
            profileinfo = self.portal_setup.getProfileInfo(profileid)
        except KeyError:
            return False
        product = profileinfo['product']

        if get_installer is not None:
            quickinstaller = get_installer(self.portal, self.portal.REQUEST)

            if (quickinstaller.is_product_installable(product)
                    and not quickinstaller.is_product_installed(product)):
                return False
        else:
            quickinstaller = getToolByName(self.portal_setup,
                                           'portal_quickinstaller')
            if (quickinstaller.isProductInstallable(product)
                    and not quickinstaller.isProductInstalled(product)):
                return False

        version = self.portal_setup.getLastVersionForProfile(profileid)
        return version != 'unknown'

    security.declarePrivate('_sort_profiles_by_dependencies')

    def _sort_profiles_by_dependencies(self, profiles):
        """Sort the profiles so that the profiles are listed after its
        dependencies since it is safer to first install dependencies.
        """

        sorted_profile_ids = get_sorted_profile_ids(self.portal_setup)
        return sorted(profiles,
                      key=lambda p: sorted_profile_ids.index(p.get('id')))

    security.declarePrivate('_is_orphan')

    def _is_orphan(self, profile, upgrade_step_info):
        if upgrade_step_info['proposed']:
            return False
        if not self._is_recordeable(upgrade_step_info):
            return False
        return not self._was_upgrade_executed(profile, upgrade_step_info)

    security.declarePrivate('_is_deferrable')

    def _is_deferrable(self, upgrade_step_info):
        step = upgrade_step_info.get('step')
        if not step:
            return False

        maybe_ftw_upgrade_step_wrapper = getattr(step, 'handler', None)
        if not maybe_ftw_upgrade_step_wrapper:
            return False

        upgrade_step_class = getattr(maybe_ftw_upgrade_step_wrapper, 'handler',
                                     None)
        if not upgrade_step_class:
            return False

        return bool(getattr(upgrade_step_class, 'deferrable', False))

    security.declarePrivate('_is_recordeable')

    def _is_recordeable(self, upgrade_step_info):
        if not isinstance(upgrade_step_info['step'], UpgradeStep):
            return False
        handler = upgrade_step_info['step'].handler
        return IRecordableHandler.providedBy(handler)

    security.declarePrivate('_was_upgrade_executed')

    def _was_upgrade_executed(self, profile, upgrade_step_info):
        """Check for whether we know if an upgrade step was executed.

        Returns True when the recorder is sure that this upgrade was executed.
        Returns False when the recorder is sure that it was not executed.
        Returns None when the recorder does not know whether this upgrade was executed.
        """
        if not self._is_recordeable(upgrade_step_info):
            return None
        else:
            recorder = getMultiAdapter((self.portal, profile),
                                       IUpgradeStepRecorder)
            return recorder.is_installed(upgrade_step_info['sdest'])
예제 #52
0
slot_events = [
    RenderLeftSlot,
    RenderRightSlot,
    RenderAboveContent,
    RenderBelowContent,
    RenderInHead,
    RenderBeforeBodyEnd,
    RenderEditInHead,
]

# BBB starts here --- --- --- --- --- ---

from zope.deprecation import deprecated

# The remainder of this file will be removed in Kotti 0.11 or 1.1, whichever
# will be the version number we chose.

from kotti.views.navigation import local_navigation
from kotti.views.navigation import includeme_local_navigation

local_navigation = local_navigation
includeme_local_navigation = includeme_local_navigation

deprecated(
    'local_navigation', 'deprecated as of Kotti 0.9.  Use '
    'kotti.views.navigation.local_navigation instead.')
deprecated(
    'includeme_local_navigation', 'deprecated as of Kotti 0.9.  Use '
    'kotti.views.navigation.includeme_local_navigation instead.')
예제 #53
0
    def __init__(self,
                 connection_id=None,
                 exchange=None,
                 routing_key=None,
                 durable=None,
                 exchange_type=None,
                 exchange_durable=None,
                 exchange_auto_delete=None,
                 exchange_auto_declare=None,
                 queue=None,
                 queue_durable=None,
                 queue_auto_delete=None,
                 queue_exclusive=None,
                 queue_arguments=None,
                 queue_auto_declare=None,
                 auto_declare=None,
                 auto_delete=None,
                 auto_ack=None,
                 marker=None):

        self._queue = None  # will default to self.queue

        # Allow class variables to provide defaults for:

        # connection_id
        if connection_id is not None:
            self.connection_id = connection_id
        assert self.connection_id is not None,\
            u"Consumer configuration is missing connection_id."

        # exchange
        if exchange is not None:
            self.exchange = exchange

        # routing_key
        if routing_key is not None:
            self.routing_key = routing_key

        # durable (and the default for exchange_durable)
        if durable is not None:
            self.durable = durable

        # auto_delete (and the default for exchange/queue_auto_delete)
        if auto_delete is not None:
            self.auto_delete = auto_delete
        elif self.auto_delete is None:
            self.auto_delete = not self.durable

        # exchange_type
        if exchange_type is not None:
            self.exchange_type = exchange_type
        # exchange_durable
        if exchange_durable is not None:
            self.exchange_durable = exchange_durable
        elif self.exchange_durable is None:
            self.exchange_durable = self.durable
        # exchange_auto_delete
        if exchange_auto_delete is not None:
            self.exchange_auto_delete = exchange_auto_delete
        elif self.exchange_auto_delete is None:
            self.exchange_auto_delete = self.auto_delete

        # queue
        if self.queue is None and queue is None:
            queue = getattr(self, 'grokcore.component.directive.name', None)
        if queue is not None:
            self._queue = self.queue = queue
        assert self.queue is not None,\
            u"Consumer configuration is missing queue."
        # routing_key
        if self.routing_key is None:
            self.routing_key = self.queue
        # queue_durable
        if queue_durable is not None:
            self.queue_durable = queue_durable
        elif self.queue_durable is None:
            self.queue_durable = self.durable
        # queue_auto_delete
        if queue_auto_delete is not None:
            self.queue_auto_delete = queue_auto_delete
        elif self.queue_auto_delete is None:
            self.queue_auto_delete = self.auto_delete
        # queue_exclusive
        if queue_exclusive is not None:
            self.queue_exclusive = queue_exclusive
        if self.queue_exclusive is True:
            self.queue_durable = False
            self.queue_auto_delete = True
        # queue_arguments
        if queue_arguments is not None:
            self.queue_arguments = queue_arguments

        # auto_declare
        if auto_declare is not None:
            self.auto_declare = auto_declare
        if exchange_auto_declare is not None:
            self.exchange_auto_declare = exchange_auto_declare
        elif self.exchange_auto_declare is None:
            self.exchange_auto_declare = self.auto_declare
        if queue_auto_declare is not None:
            self.queue_auto_declare = queue_auto_declare
        elif self.queue_auto_declare is None:
            self.queue_auto_declare = self.auto_declare

        # auto_ack
        if auto_ack is not None:
            self.auto_ack = auto_ack

        # marker
        if marker is not None:
            self.marker = marker

        # BBB for affinitic.zamqp
        if getattr(self, "messageInterface", None):
            from zope.deprecation import deprecated
            self.marker = self.messageInterface
            self.messageInterface =\
                deprecated(self.messageInterface,
                           ('Consumer.messageInterface is no more. '
                            'Please, use Consumer.marker instead.'))
예제 #54
0
    if title:
        return title
    item_id = getattr(obj, 'getId', None)
    if safe_callable(item_id):
        item_id = item_id()
    if item_id and not isIDAutoGenerated(context, item_id):
        return item_id
    if empty_value is _marker:
        empty_value = getEmptyTitle(context)
    return empty_value


def getSiteEncoding(context):
    return 'utf-8'
deprecated('getSiteEncoding',
           ('`getSiteEncoding` is deprecated. Plone only supports UTF-8 '
            'currently. This method always returns "utf-8"'))

# XXX portal_utf8 and utf8_portal probably can go away
def portal_utf8(context, str, errors='strict'):
    # Test
    unicode(str, 'utf-8', errors)
    return str


# XXX this is the same method as above
def utf8_portal(context, str, errors='strict'):
    # Test
    unicode(str, 'utf-8', errors)
    return str
예제 #55
0
        renderer), ``context`` (the context object passed to the
        view), and ``request`` (the request object passed to the
        view)."""


class ITemplateRenderer(IRenderer):
    def implementation():
        """ Return the object that the underlying templating system
        uses to render the template; it is typically a callable that
        accepts arbitrary keyword arguments and returns a string or
        unicode object """


deprecated(
    'ITemplateRenderer',
    'As of Pyramid 1.5 the, "pyramid.interfaces.ITemplateRenderer" interface '
    'is scheduled to be removed. It was used by the Mako and Chameleon '
    'renderers which have been split into their own packages.')


class IViewMapper(Interface):
    def __call__(self, object):
        """ Provided with an arbitrary object (a function, class, or
        instance), returns a callable with the call signature ``(context,
        request)``.  The callable returned should itself return a Response
        object.  An IViewMapper is returned by
        :class:`pyramid.interfaces.IViewMapperFactory`."""


class IViewMapperFactory(Interface):
    def __call__(self, **kw):
예제 #56
0
        """

    def isCanonical():
        """
        boolean, is this the original, canonical translation of the content.
        """

    def getCanonicalLanguage():
        """
        Return the language code for the canonical translation of this content.
        """

    def getCanonical():
        """
        Return the original, canonical translation of this content.
        """

    def setLanguage(language):
        """
        Sets the language for the current translation - same as DC
        """

    def Language():
        """
        Returns the language of this translation - same as DC
        """

deprecated("ITranslatable",
           "Please use Products.LinguaPlone.interfaces.ITranslatable instead. "
           "This interface will be removed in Plone 5.0")
예제 #57
0
from zope.deprecation import deprecated
from plumber._behavior import Behavior
from plumber._plumber import plumber
from plumber._instructions import default
from plumber._instructions import override
from plumber._instructions import finalize
from plumber._instructions import plumb
from plumber._instructions import plumbifexists

Part = Behavior  # B/C
deprecated(
    'Part', """
``plumber.Part`` is deprecated as of plumber 1.2 and will be removed in
plumber 1.3. Use ``plumber.Behavior`` instead.""")

extend = override  # B/C
deprecated(
    'extend', """
``plumber.extend`` is deprecated as of plumber 1.2 and will be removed in 
plumber 1.3. Use ``plumber.override`` instead.""")
예제 #58
0

class ProposalSchema(colander.MappingSchema):

    """Data structure for organizational information."""

    # TODO: check exact length restrictions

    budget = CurrencyAmount(missing=colander.required,
                            validator=colander.Range(min=0, max=50000))
    creator_participate = Boolean()
    location_text = SingleLine(validator=colander.Length(max=100))
    address = Text()

proposal_meta = sheet_meta._replace(isheet=IProposal,
                                    schema_class=ProposalSchema)


class IWorkflowAssignment(workflow.IWorkflowAssignment):

    """Marker interface for the kiezkassen workflow assignment sheet."""


deprecated('IWorkflowAssignment',
           'Backward compatible code use IWorkflowAssignment instead')


def includeme(config):
    """Register sheets."""
    add_sheet_to_registry(proposal_meta, config.registry)