Exemple #1
0
def wrap_method(klass, name, method,
                pattern=PATTERN, add=False, roles=None, deprecated=False):
    """takes a method and set it to a class. Annotates with hints what happened.
    """
    new_name = pattern % name
    if not add:
        old_method = getattr(klass, name)
        if isWrapperMethod(old_method):
            logger.warn(
                'PlonePAS: *NOT* wrapping already wrapped method at '
                '{0}.{1}'.format(
                    klass.__name__, name)
            )

            return
        logger.debug(
            'PlonePAS: Wrapping method at %s.%s',
            klass.__name__, name
        )
        setattr(klass, new_name, old_method)
        setattr(method, ORIG_NAME, new_name)
        setattr(method, WRAPPER, True)
        setattr(method, ADDED, False)
    else:
        logger.debug('PlonePAS: Adding method at %s.%s', klass.__name__, name)
        setattr(method, WRAPPER, False)
        setattr(method, ADDED, True)

    if deprecated:
        setattr(klass, name, deprecation.deprecated(method, deprecated))
    else:
        setattr(klass, name, method)

    if roles is not None:
        roles_attr = '{0}__roles__'.format(name)
        logger.debug(
            'PlonePAS: Setting new permission roles at {0}.{1}'.format(
                klass.__name__, name
            )
        )
        setattr(klass, roles_attr, roles)
Exemple #2
0
def wrap_method(klass,
                name,
                method,
                pattern=PATTERN,
                add=False,
                roles=None,
                deprecated=False):
    """takes a method and set it to a class. Annotates with hints what happened.
    """
    new_name = pattern % name
    if not add:
        old_method = getattr(klass, name)
        if isWrapperMethod(old_method):
            logger.warn('PlonePAS: *NOT* wrapping already wrapped method at '
                        '{0}.{1}'.format(klass.__name__, name))

            return
        logger.debug('PlonePAS: Wrapping method at %s.%s', klass.__name__,
                     name)
        setattr(klass, new_name, old_method)
        setattr(method, ORIG_NAME, new_name)
        setattr(method, WRAPPER, True)
        setattr(method, ADDED, False)
    else:
        logger.debug('PlonePAS: Adding method at %s.%s', klass.__name__, name)
        setattr(method, WRAPPER, False)
        setattr(method, ADDED, True)

    if deprecated:
        setattr(klass, name, deprecation.deprecated(method, deprecated))
    else:
        setattr(klass, name, method)

    if roles is not None:
        roles_attr = '{0}__roles__'.format(name)
        logger.debug(
            'PlonePAS: Setting new permission roles at {0}.{1}'.format(
                klass.__name__, name))
        setattr(klass, roles_attr, roles)
Exemple #3
0
 def _callFUT(self, spec, message):
     from zope.deprecation.deprecation import deprecated
     return deprecated(spec, message)
Exemple #4
0
RESET_PASSWORD_SUBJECT = u"Reset your password for %(site_title)s."
RESET_PASSWORD_BODY = u"""Hello, %(user_title)s!

Click this link to reset your password at %(site_title)s: %(url)s.
"""

message_templates = {
    'set-password': dict(
        subject=SET_PASSWORD_SUBJECT, body=SET_PASSWORD_BODY),
    'reset-password': dict(
        subject=RESET_PASSWORD_SUBJECT, body=RESET_PASSWORD_BODY),
    }
deprecated(
    'message_templates',
    'message_templates is deprecated as of Kotti 0.6.4.  '
    'Use the ``email-set-password.pt`` and ``email-reset-password.pt`` '
    'templates instead.'
    )

_inject_mailer = []


def get_mailer():
    # Consider that we may have persistent settings
    if _inject_mailer:
        return _inject_mailer[0]
    return Mailer.from_settings(get_settings())  # pragma: no cover


def make_token(user, seconds=None):
    secret = get_settings()['kotti.secret2']
Exemple #5
0
    settings = _resolve_dotted(get_settings())
    tables = settings['kotti.use_tables'].strip() or None
    if tables:
        tables = [metadata.tables[name] for name in tables.split()]

    _adjust_for_engine(engine)

    # Allow migrations to set the 'head' stamp in case the database is
    # initialized freshly:
    if not engine.table_names():
        stamp_heads()

    metadata.create_all(engine, tables=tables)
    if os.environ.get('KOTTI_DISABLE_POPULATORS', '0') not in TRUE_VALUES:
        for populate in settings['kotti.populators']:
            populate()
    commit()

    return DBSession


# DEPRECATED

from zope.deprecation.deprecation import deprecated
from kotti_image.resources import Image

__ = Image
deprecated(
    'Image', 'Image was outfactored to the kotti_image package.  '
    'Please import from there.')
Exemple #6
0
        "kotti.populators": "kotti.populate.populate_users",
        "pyramid.includes": "kotti.testing.include_testing_view",
        "kotti.root_factory": "kotti.testing.RootFactory",
        "kotti.site_title": "My Stripped Down Kotti",
    }
    _settings.update(settings)

    return setUpFunctional(global_config, **_settings)


# noinspection PyPep8Naming
def registerDummyMailer():
    from pyramid_mailer.mailer import DummyMailer
    from kotti.message import _inject_mailer

    mailer = DummyMailer()
    _inject_mailer.append(mailer)
    return mailer


# set up deprecation warnings
from zope.deprecation.deprecation import deprecated  # noqa

for item in UnitTestBase, EventTestBase, FunctionalTestBase, _init_testing_db:
    name = getattr(item, "__name__", item)
    deprecated(
        name,
        "Unittest-style tests are deprecated as of Kotti 0.7. "
        "Please use pytest function arguments instead.",
    )
Exemple #7
0
    def get_cluster(self, project_id, region, cluster_name):
        return self.get_conn().projects().regions().clusters().get(
            projectId=project_id, region=region,
            clusterName=cluster_name).execute(num_retries=5)

    def submit(self, project_id, job, region='global', job_error_states=None):
        submitted = _DataProcJob(self.get_conn(),
                                 project_id,
                                 job,
                                 region,
                                 job_error_states=job_error_states)
        if not submitted.wait_for_done():
            submitted.raise_error()

    def create_job_template(self, task_id, cluster_name, job_type, properties):
        return _DataProcJobBuilder(self.project_id, task_id, cluster_name,
                                   job_type, properties)

    def wait(self, operation):
        """Awaits for Google Cloud Dataproc Operation to complete."""
        submitted = _DataProcOperation(self.get_conn(), operation)
        submitted.wait_for_done()


setattr(
    DataProcHook,
    "await",
    deprecation.deprecated(DataProcHook.wait,
                           "renamed to 'wait' for Python3.7 compatibility"),
)
Exemple #8
0
from pyramid_beaker import session_factory_from_settings

from kotti.sqla import Base as KottiBase

metadata = MetaData()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base(cls=KottiBase)
Base.metadata = metadata
Base.query = DBSession.query_property()
TRUE_VALUES = ('1', 'y', 'yes', 't', 'true')
FALSE_VALUES = ('0', 'n', 'no', 'f', 'false', 'none')

# BBB module deprecation
from kotti import fanstatic
sys.modules['kotti.static'] = deprecation.deprecated(
    fanstatic,
    "The module kotti.static has been moved to kotti.fanstatic as of Kotti "
    "0.8. Import from there instead.")


def authtkt_factory(**settings):
    from kotti.security import list_groups_callback
    kwargs = dict(
        secret=settings['kotti.secret2'],
        hashalg='sha512',
        callback=list_groups_callback,
    )
    try:
        return AuthTktAuthenticationPolicy(**kwargs)
    except TypeError:
        # BBB with Pyramid < 1.4
        kwargs.pop('hashalg')
POD_FORMATS = ODS_FORMATS + ODT_FORMATS + NEUTRAL_FORMATS

DEFAULT_PYTHON_UNO_PATH = u'/usr/bin/python'

VIEWLET_TYPES = ['PODTemplate', 'ConfigurablePODTemplate']

HAS_PLONE_5 = api.env.plone_version().startswith('5')
HAS_PLONE_5_1 = api.env.plone_version() > '5.1'
HAS_PLONE_5_2 = api.env.plone_version() > '5.2'

if HAS_PLONE_5_2:
    import sys
    from zope.deprecation import deprecation
    sys.modules['collective.documentgenerator.demo.helper.ATDemoHelperView'] = \
        deprecation.deprecated(deprecation, 'Archetypes was removed from Plone 5.2.')


def get_uno_path():
    return api.portal.get_registry_record(
        'collective.documentgenerator.browser.controlpanel.IDocumentGeneratorControlPanelSchema.uno_path'
    )


def get_oo_server():
    return api.portal.get_registry_record(
        'collective.documentgenerator.browser.controlpanel.IDocumentGeneratorControlPanelSchema.oo_server'
    )


def get_oo_port():
Exemple #10
0
    if engine.dialect.name == 'mysql':  # pragma: no cover
        from sqlalchemy.dialects.mysql.base import LONGBLOB
        File.__table__.c.data.type = LONGBLOB()

    # Allow migrations to set the 'head' stamp in case the database is
    # initialized freshly:
    if not engine.table_names():
        stamp_heads()

    metadata.create_all(engine, tables=tables)
    if os.environ.get('KOTTI_DISABLE_POPULATORS', '0') not in ('1', 'y'):
        for populate in get_settings()['kotti.populators']:
            populate()
    commit()

    return DBSession


def appmaker(engine):
    initialize_sql(engine)
    return get_root


# BBB
for iface in ("INode", "IContent", "IDocument", "IFile", "IImage",
              "IDefaultWorkflow"):
    deprecated(
        iface, "%s has been moved to kotti.interfaces as of Kotti 0.8. "
        "Import from there instead." % iface)
Exemple #11
0
    """ Pyramid includeme hook.

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

    config.scan(__name__)


# DEPRECATED

# noinspection PyPep8
from zope.deprecation.deprecation import deprecated
# noinspection PyPep8
from kotti.filedepot import StoredFileResponse


class UploadedFileResponse(StoredFileResponse):
    def __init__(self, data, request, disposition='attachment',
                 cache_max_age=None, content_type=None,
                 content_encoding=None):
        super(UploadedFileResponse, self).__init__(
            data.file, request, disposition=disposition,
            cache_max_age=cache_max_age, content_type=content_type,
            content_encoding=content_encoding)

deprecated('UploadedFileResponse',
           'UploadedFileResponse is deprecated and will be removed in '
           'Kotti 2.0.0.  Use "request.uploaded_file_response(context.data)" '
           'instead.')
            projectId=project_id,
            region=region,
            clusterName=cluster_name
        ).execute(num_retries=self.num_retries)

    def submit(self, project_id, job, region='global', job_error_states=None):
        submitted = _DataProcJob(self.get_conn(), project_id, job, region,
                                 job_error_states=job_error_states,
                                 num_retries=self.num_retries)
        if not submitted.wait_for_done():
            submitted.raise_error()

    def create_job_template(self, task_id, cluster_name, job_type, properties):
        return _DataProcJobBuilder(self.project_id, task_id, cluster_name,
                                   job_type, properties)

    def wait(self, operation):
        """Awaits for Google Cloud Dataproc Operation to complete."""
        submitted = _DataProcOperation(self.get_conn(), operation,
                                       self.num_retries)
        submitted.wait_for_done()


setattr(
    DataProcHook,
    "await",
    deprecation.deprecated(
        DataProcHook.wait, "renamed to 'wait' for Python3.7 compatibility"
    ),
)
Exemple #13
0
        'kotti.populators': 'kotti.populate.populate_users',
        'pyramid.includes': 'kotti.testing.include_testing_view',
        'kotti.root_factory': 'kotti.testing.RootFactory',
        'kotti.site_title': 'My Stripped Down Kotti',
        }
    _settings.update(settings)

    return setUpFunctional(global_config, **_settings)


def registerDummyMailer():
    from pyramid_mailer.mailer import DummyMailer
    from kotti.message import _inject_mailer

    mailer = DummyMailer()
    _inject_mailer.append(mailer)
    return mailer


# set up deprecation warnings
from zope.deprecation.deprecation import deprecated  # noqa
for item in UnitTestBase, EventTestBase, FunctionalTestBase, _initTestingDB:
    name = getattr(item, '__name__', item)
    deprecated(name, 'Unittest-style tests are deprecated as of Kotti 0.7. '
               'Please use pytest function arguments instead.')

TestingRootFactory = RootFactory
deprecated('TestingRootFactory',
           "TestingRootFactory has been renamed to RootFactory and will be no "
           "longer available starting with Kotti 2.0.0.")
Exemple #14
0
    # Allow users of Kotti to cherry pick the tables that they want to use:
    settings = _resolve_dotted(get_settings())
    tables = settings["kotti.use_tables"].strip() or None
    if tables:
        tables = [metadata.tables[name] for name in tables.split()]

    _adjust_for_engine(engine)

    # Allow migrations to set the 'head' stamp in case the database is
    # initialized freshly:
    if not engine.table_names():
        stamp_heads()

    metadata.create_all(engine, tables=tables)
    if os.environ.get("KOTTI_DISABLE_POPULATORS", "0") not in TRUE_VALUES:
        for populate in settings["kotti.populators"]:
            populate()
    commit()

    return DBSession


# DEPRECATED

from zope.deprecation.deprecation import deprecated
from kotti_image.resources import Image

__ = Image
deprecated("Image", "Image was outfactored to the kotti_image package.  " "Please import from there.")
Exemple #15
0
    settings = _resolve_dotted(get_settings())
    tables = settings['kotti.use_tables'].strip() or None
    if tables:
        tables = [metadata.tables[name] for name in tables.split()]

    _adjust_for_engine(engine)

    # Allow migrations to set the 'head' stamp in case the database is
    # initialized freshly:
    if not engine.table_names():
        stamp_heads()

    metadata.create_all(engine, tables=tables)
    if os.environ.get('KOTTI_DISABLE_POPULATORS', '0') not in TRUE_VALUES:
        for populate in settings['kotti.populators']:
            populate()
    commit()

    return DBSession


# DEPRECATED

from zope.deprecation.deprecation import deprecated
from kotti_image.resources import Image

__ = Image
deprecated('Image',
           'Image was outfactored to the kotti_image package.  '
           'Please import from there.')
Exemple #16
0
    """This event is emitted when an object in the DB is updated."""


class ObjectDelete(ObjectEvent):
    """This event is emitted when an object is deleted from the DB."""


class ObjectAfterDelete(ObjectEvent):
    """This event is emitted after an object has been deleted from the DB.

    .. deprecated:: 0.9
    """


deprecated(
    'ObjectAfterDelete',
    "The ObjectAfterDelete event is deprecated and will be no longer "
    "available starting with Kotti 0.10.")


class UserDeleted(ObjectEvent):
    """This event is emitted when an user object is deleted from the DB."""


class DispatcherDict(defaultdict, OrderedDict):
    """Base class for dispatchers"""
    def __init__(self, *args, **kwargs):
        defaultdict.__init__(self, list)
        OrderedDict.__init__(self, *args, **kwargs)


class Dispatcher(DispatcherDict):
Exemple #17
0
 def _callFUT(self, spec, message, *args):
     from zope.deprecation.deprecation import deprecated
     return deprecated(spec, message, *args)
Exemple #18
0
    # 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:
        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()

    # Allow migrations to set the 'head' stamp in case the database is
    # initialized freshly:
    if not engine.table_names():
        stamp_heads()

    metadata.create_all(engine, tables=tables)
    if os.environ.get('KOTTI_DISABLE_POPULATORS', '0') not in ('1', 'y'):
        for populate in get_settings()['kotti.populators']:
            populate()
    commit()

    return DBSession


# BBB
for iface in ("INode", "IContent", "IDocument", "IFile", "IImage",
              "IDefaultWorkflow"):
    deprecated(iface,
               "%s has been moved to kotti.interfaces as of Kotti 0.8. "
               "Import from there instead." % iface)
Exemple #19
0
class DeprecatedRequestMethodsMixin(object):

    # b/c dict interface for "root factory" code that expects a bare
    # environ.  Explicitly omitted dict methods: clear (unnecessary),
    # copy (implemented by WebOb), fromkeys (unnecessary); deprecated
    # as of Pyramid 1.1.

    dictlike = ('Use of the request as a dict-like object is deprecated as '
                'of Pyramid 1.1.  Use dict-like methods of "request.environ" '
                'instead.')

    @deprecate(dictlike)
    def __contains__(self, k):
        return self.environ.__contains__(k)

    @deprecate(dictlike)
    def __delitem__(self, k):
        return self.environ.__delitem__(k)

    @deprecate(dictlike)
    def __getitem__(self, k):
        return self.environ.__getitem__(k)

    @deprecate(dictlike)
    def __iter__(self):
        return iter(self.environ)

    @deprecate(dictlike)
    def __setitem__(self, k, v):
        self.environ[k] = v

    @deprecate(dictlike)
    def get(self, k, default=None):
        return self.environ.get(k, default)

    @deprecate(dictlike)
    def has_key(self, k):
        return k in self.environ

    @deprecate(dictlike)
    def items(self):
        return self.environ.items()

    @deprecate(dictlike)
    def iteritems(self):
        return iteritems_(self.environ)

    @deprecate(dictlike)
    def iterkeys(self):
        return iterkeys_(self.environ)

    @deprecate(dictlike)
    def itervalues(self):
        return itervalues_(self.environ)

    @deprecate(dictlike)
    def keys(self):
        return self.environ.keys()

    @deprecate(dictlike)
    def pop(self, k):
        return self.environ.pop(k)

    @deprecate(dictlike)
    def popitem(self):
        return self.environ.popitem()

    @deprecate(dictlike)
    def setdefault(self, v, default):
        return self.environ.setdefault(v, default)

    @deprecate(dictlike)
    def update(self, v, **kw):
        return self.environ.update(v, **kw)

    @deprecate(dictlike)
    def values(self):
        return self.environ.values()

    # 1.0 deprecated bw compat code for using response_* values

    rr_dep = ('Accessing and setting "request.response_%s" is '
              'deprecated as of Pyramid 1.1; access or set '
              '"request.response.%s" instead.')

    # response_content_type
    def _response_content_type_get(self):
        return self._response_content_type

    def _response_content_type_set(self, value):
        self._response_content_type = value

    def _response_content_type_del(self):
        del self._response_content_type

    response_content_type = property(_response_content_type_get,
                                     _response_content_type_set,
                                     _response_content_type_del)
    response_content_type = deprecated(
        response_content_type, rr_dep % ('content_type', 'content_type'))

    # response_headerlist
    def _response_headerlist_get(self):
        return self._response_headerlist

    def _response_headerlist_set(self, value):
        self._response_headerlist = value

    def _response_headerlist_del(self):
        del self._response_headerlist

    response_headerlist = property(_response_headerlist_get,
                                   _response_headerlist_set,
                                   _response_headerlist_del)

    hl_dep = ('Accessing and setting "request.response_headerlist" is '
              'deprecated as of Pyramid 1.1; access the headerlist via '
              '"request.response.headerlist" and extend headers via '
              '"request.response.headerlist.extend(alist)" instead of '
              '"request.response_headerlist = alist"')

    response_headerlist = deprecated(response_headerlist, hl_dep)

    # response_status
    def _response_status_get(self):
        return self._response_status

    def _response_status_set(self, value):
        self._response_status = value

    def _response_status_del(self):
        del self._response_status

    response_status = property(_response_status_get, _response_status_set,
                               _response_status_del)

    response_status = deprecated(response_status,
                                 rr_dep % ('status', 'status'))

    # response_charset
    def _response_charset_get(self):
        return self._response_charset

    def _response_charset_set(self, value):
        self._response_charset = value

    def _response_charset_del(self):
        del self._response_charset

    response_charset = property(_response_charset_get, _response_charset_set,
                                _response_charset_del)
    response_charset = deprecated(response_charset,
                                  rr_dep % ('charset', 'charset'))

    # response_cache_for
    def _response_cache_for_get(self):
        return self._response_cache_for

    def _response_cache_for_set(self, value):
        self._response_cache_for = value

    def _response_cache_for_del(self):
        del self._response_cache_for

    response_cache_for = property(_response_cache_for_get,
                                  _response_cache_for_set,
                                  _response_cache_for_del)
    response_cache_for = deprecated(response_cache_for,
                                    rr_dep % ('cache_for', 'cache_expires'))
Exemple #20
0
"""

RESET_PASSWORD_SUBJECT = u"Reset your password for %(site_title)s."
RESET_PASSWORD_BODY = u"""Hello, %(user_title)s!

Click this link to reset your password at %(site_title)s: %(url)s.
"""

message_templates = {
    'set-password':
    dict(subject=SET_PASSWORD_SUBJECT, body=SET_PASSWORD_BODY),
    'reset-password':
    dict(subject=RESET_PASSWORD_SUBJECT, body=RESET_PASSWORD_BODY),
}
deprecated(
    'message_templates', 'message_templates is deprecated as of Kotti 0.6.4.  '
    'Use the ``email-set-password.pt`` and ``email-reset-password.pt`` '
    'templates instead.')

_inject_mailer = []


def get_mailer():
    # Consider that we may have persistent settings
    if _inject_mailer:
        return _inject_mailer[0]
    return Mailer.from_settings(get_settings())  # pragma: no cover


def make_token(user, seconds=None):
    secret = get_settings()['kotti.secret2']
    if seconds is None:
Exemple #21
0
class ObjectUpdate(ObjectEvent):
    """This event is emitted when an object in the DB is updated."""


class ObjectDelete(ObjectEvent):
    """This event is emitted when an object is deleted from the DB."""


class ObjectAfterDelete(ObjectEvent):
    """This event is emitted after an object has been deleted from the DB.

    .. deprecated:: 0.9
    """
deprecated('ObjectAfterDelete',
           "The ObjectAfterDelete event is deprecated and will be no longer "
           "available starting with Kotti 0.10.")


class UserDeleted(ObjectEvent):
    """This event is emitted when an user object is deleted from the DB."""


class DispatcherDict(defaultdict, OrderedDict):
    """Base class for dispatchers"""

    def __init__(self, *args, **kwargs):
        defaultdict.__init__(self, list)
        OrderedDict.__init__(self, *args, **kwargs)

Exemple #22
0
            ("Content-Type", str(context.mimetype)),
        ]
    )
    res.body = context.data
    return res


@view_config(name="attachment-view", context=File, permission="view")
def attachment_view(context, request):
    return inline_view(context, request, "attachment")


def includeme(config):
    config.scan(__name__)


# BBB
from .edit.content import FileAddForm as AddFileFormView
from .edit.content import ImageAddForm as AddImageFormView
from .edit.content import FileEditForm as EditFileFormView
from .edit.content import ImageEditForm as EditImageFormView

for cls in (AddFileFormView, AddImageFormView, EditFileFormView, EditImageFormView):
    deprecated(
        cls,
        """\
%s has been renamed (e.g. 'FileAddForm' became 'AddFileFormView') and moved to
kottiv.views.edit.content as of Kotti 0.8."""
        % cls.__name__,
    )
Exemple #23
0
        "kotti.root_factory":
        "kotti.testing.RootFactory",
        "kotti.site_title":
        "My Stripped Down Kotti",
    }
    _settings.update(settings)

    return setUpFunctional(global_config, **_settings)


# noinspection PyPep8Naming
def registerDummyMailer():
    from pyramid_mailer.mailer import DummyMailer
    from kotti.message import _inject_mailer

    mailer = DummyMailer()
    _inject_mailer.append(mailer)
    return mailer


# set up deprecation warnings
from zope.deprecation.deprecation import deprecated  # noqa

for item in UnitTestBase, EventTestBase, FunctionalTestBase, _init_testing_db:
    name = getattr(item, "__name__", item)
    deprecated(
        name,
        "Unittest-style tests are deprecated as of Kotti 0.7. "
        "Please use pytest function arguments instead.",
    )
Exemple #24
0

@view_config(name='attachment-view', context=IFile, permission='view')
def attachment_view(context, request):
    return request.uploaded_file_response(context.data, 'attachment')


def includeme(config):
    config.scan(__name__)


# DEPRECATED

from zope.deprecation.deprecation import deprecated
from kotti.filedepot import StoredFileResponse


class UploadedFileResponse(StoredFileResponse):
    def __init__(self, data, request, disposition='attachment',
                 cache_max_age=None, content_type=None,
                 content_encoding=None):
        super(UploadedFileResponse, self).__init__(
            data.file, request, disposition=disposition,
            cache_max_age=cache_max_age, content_type=content_type,
            content_encoding=content_encoding)

deprecated('UploadedFileResponse',
           'UploadedFileResponse is deprecated and will be removed in '
           'Kotti 2.0.0.  Use "request.uploaded_file_response(context.data)" '
           'instead.')
Exemple #25
0
        'kotti.site_title':
        'My Stripped Down Kotti',
    }
    _settings.update(settings)

    return setUpFunctional(global_config, **_settings)


def registerDummyMailer():
    from pyramid_mailer.mailer import DummyMailer
    from kotti.message import _inject_mailer

    mailer = DummyMailer()
    _inject_mailer.append(mailer)
    return mailer


# set up deprecation warnings
from zope.deprecation.deprecation import deprecated  # noqa
for item in UnitTestBase, EventTestBase, FunctionalTestBase, _initTestingDB:
    name = getattr(item, '__name__', item)
    deprecated(
        name, 'Unittest-style tests are deprecated as of Kotti 0.7. '
        'Please use pytest function arguments instead.')

TestingRootFactory = RootFactory
deprecated(
    'TestingRootFactory',
    "TestingRootFactory has been renamed to RootFactory and will be no "
    "longer available starting with Kotti 2.0.0.")
Exemple #26
0
    :param context: context that should be checked for the given permission
    :type context: :class:``kotti.resources.Node``

    :param request: current request
    :type request: :class:`kotti.request.Request`

    :result: ``True`` if request has the permission, ``False`` else
    :rtype: bool
    """

    return request.has_permission(permission, context)


deprecated(u'has_permission',
           u"kotti.security.has_permission is deprecated as of Kotti 1.0 and "
           u"will be no longer available starting with Kotti 2.0.  "
           u"Please use the has_permission method of request instead.")


class Principal(Base):
    """A minimal 'Principal' implementation.

    The attributes on this object correspond to what one ought to
    implement to get full support by the system.  You're free to add
    additional attributes.

      - As convenience, when passing 'password' in the initializer, it
        is hashed using 'get_principals().hash_password'

      - The boolean 'active' attribute defines whether a principal may
        log in.  This allows the deactivation of accounts without
Exemple #27
0
    :param context: context that should be checked for the given permission
    :type context: :class:``kotti.resources.Node``

    :param request: current request
    :type request: :class:`kotti.request.Request`

    :result: ``True`` if request has the permission, ``False`` else
    :rtype: bool
    """

    return request.has_permission(permission, context)


deprecated(
    u'has_permission',
    u"kotti.security.has_permission is deprecated as of Kotti 1.0 and "
    u"will be no longer available starting with Kotti 2.0.  "
    u"Please use the has_permission method of request instead.")


class Principal(Base):
    """A minimal 'Principal' implementation.

    The attributes on this object correspond to what one ought to
    implement to get full support by the system.  You're free to add
    additional attributes.

      - As convenience, when passing 'password' in the initializer, it
        is hashed using 'get_principals().hash_password'

      - The boolean 'active' attribute defines whether a principal may
Exemple #28
0
from kotti.sqla import Base as KottiBase


metadata = MetaData()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base(cls=KottiBase)
Base.metadata = metadata
Base.query = DBSession.query_property()
TRUE_VALUES = ('1', 'y', 'yes', 't', 'true')
FALSE_VALUES = ('0', 'n', 'no', 'f', 'false', 'none')


# BBB module deprecation
from kotti import fanstatic
sys.modules['kotti.static'] = deprecation.deprecated(
    fanstatic,
    "The module kotti.static has been moved to kotti.fanstatic as of Kotti "
    "0.8. Import from there instead.")


def authtkt_factory(**settings):
    from kotti.security import list_groups_callback
    kwargs = dict(
        secret=settings['kotti.secret2'],
        hashalg='sha512',
        callback=list_groups_callback,
        )
    try:
        return AuthTktAuthenticationPolicy(**kwargs)
    except TypeError:
        # BBB with Pyramid < 1.4
        kwargs.pop('hashalg')