Exemplo n.º 1
0
 def __init__(self, repo, source_config, eid=None):
     self.repo = repo
     self.set_schema(repo.schema)
     self.eid = eid
     self.public_config = source_config.copy()
     self.public_config['use-cwuri-as-url'] = self.use_cwuri_as_url
     self.remove_sensitive_information(self.public_config)
     self.uri = source_config.pop('uri')
     # unormalize to avoid non-ascii characters in logger's name, this will cause decoding error
     # on logging
     set_log_methods(self, getLogger('cubicweb.sources.' + unormalize(self.uri)))
     source_config.pop('type')
     self.config = self._check_config_dict(
         eid, source_config, raise_on_error=False)
Exemplo n.º 2
0
        self.appli = CubicWebPublisher(config.repository(), config)
        self.config = config
        self.base_url = self.config['base-url']
        self.url_rewriter = self.appli.vreg['components'].select_or_none(
            'urlrewriter')

    def _render(self, req):
        """this function performs the actual rendering
        """
        try:
            result = self.appli.handle_request(req)
        except DirectResponse as ex:
            return ex.response
        return WSGIResponse(req.status_out, req, result)

    def __call__(self, environ, start_response):
        """WSGI protocol entry point"""
        req = CubicWebWsgiRequest(environ, self.appli.vreg)
        response = self._render(req)
        start_response(response.status, response.headers)
        return response.body

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


from logging import getLogger
from cubicweb import set_log_methods
set_log_methods(CubicWebWSGIApplication, getLogger('cubicweb.wsgi'))
Exemplo n.º 3
0
                if optdict.get('default') is REQUIRED:
                    self.config.input_option(optdescr[1], optdict)
        self.config.generate_config(open(newconfig, 'w'))
        show_diffs(configfile, newconfig, askconfirm=self.confirm is not yes)
        os.close(fd)
        if exists(newconfig):
            os.unlink(newconfig)

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


from logging import getLogger
from cubicweb import set_log_methods
set_log_methods(MigrationHelper, getLogger('cubicweb.migration'))


def version_strictly_lower(a, b):
    if a is None:
        return True
    if b is None:
        return False
    if a:
        a = Version(a)
    if b:
        b = Version(b)
    return a < b


def max_version(a, b):
Exemplo n.º 4
0
    def open_session(self, req):
        """open and return a new session for the given request.

        raise :exc:`cubicweb.AuthenticationError` if authentication failed
        (no authentication info found or wrong user/password)
        """
        raise NotImplementedError()

    def close_session(self, session):
        """close session on logout or on invalid session detected (expired out,
        corrupted...)
        """
        raise NotImplementedError()


set_log_methods(AbstractSessionManager, getLogger('cubicweb.sessionmanager'))


class InMemoryRepositorySessionManager(AbstractSessionManager):
    """manage session data associated to a session identifier"""
    def __init__(self, *args, **kwargs):
        super(InMemoryRepositorySessionManager, self).__init__(*args, **kwargs)
        # XXX require a RepositoryAuthenticationManager which violates
        #     authenticate interface by returning a session instead of a user
        #assert isinstance(self.authmanager, RepositoryAuthenticationManager)
        self._sessions = {}

    # dump_data / restore_data to avoid loosing open sessions on registry
    # reloading
    def dump_data(self):
        return self._sessions
Exemplo n.º 5
0
    # special case handling

    def need_login_content(self, req):
        return self.vreg['views'].main_template(req, 'login')

    def loggedout_content(self, req):
        return self.vreg['views'].main_template(req, 'loggedout')

    def notfound_content(self, req):
        req.form['vid'] = '404'
        view = self.vreg['views'].select('404', req)
        template = self.main_template_id(req)
        return self.vreg['views'].main_template(req, template, view=view)

    # template stuff

    def main_template_id(self, req):
        template = req.form.get('__template',
                                req.property_value('ui.main-template'))
        if template not in self.vreg['views']:
            template = 'main-template'
        return template

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


set_log_methods(CubicWebPublisher, LOGGER)
set_log_methods(CookieSessionHandler, LOGGER)
Exemplo n.º 6
0
    def owns(self, eid):
        return True

    def property_value(self, key):
        if key == 'ui.language':
            return self.lang
        return None

    def prefered_language(self, language=None):
        # mock CWUser.prefered_language, mainly for testing purpose
        return self.property_value('ui.language')

    # CWUser compat for notification ###########################################

    def name(self):
        return ''

    class _IEmailable:
        @staticmethod
        def get_email():
            return ''

    def cw_adapt_to(self, iface):
        if iface == 'IEmailable':
            return self._IEmailable
        return None


set_log_methods(Connection, getLogger('cubicweb.session'))
Exemplo n.º 7
0
                    continue
                other_params[infokey] = infoval
        parsed_value = value_parser(value,
                                    other_params) if value_parser else value
        values.append((value.strip(), parsed_value, score))
    values.sort(key=value_sort_key)
    return values


def _mimetype_parser(value, other_params):
    """return a 3-tuple
    (type, subtype, type_params) corresponding to the mimetype definition
    e.g. : for 'text/*', `mimetypeinfo` will be ('text', '*', {}), for
    'text/html;level=1', `mimetypeinfo` will be ('text', '*', {'level': '1'})
    """
    try:
        media_type, media_subtype = value.strip().split('/', 1)
    except ValueError:  # safety belt : '/' should always be present
        media_type = value.strip()
        media_subtype = '*'
    return (media_type, media_subtype, other_params)


ACCEPT_HEADER_PARSER = {
    'accept': (_mimetype_parser, _mimetype_sort_key),
    'accept-charset': (None, _charset_sort_key),
}

from cubicweb import set_log_methods
set_log_methods(_CubicWebRequestBase, LOGGER)
Exemplo n.º 8
0
        try:
            etype = type_from_eid(args[key], cnx)
        except KeyError:
            raise QueryError('bad cache key %s (no value)' % key)
        except TypeError:
            raise QueryError('bad cache key %s (value: %r)' % (key, args[key]))
        cachekey.append(etype)
        # ensure eid is correctly typed in args
        args[key] = int(args[key])
    return tuple(cachekey)


from logging import getLogger
from cubicweb import set_log_methods
LOGGER = getLogger('cubicweb.querier')
set_log_methods(QuerierHelper, LOGGER)


def manual_build_descr(cnx, rqlst, args, result):
    """build a description for a given result by analysing each row

    XXX could probably be done more efficiently during execution of query
    """
    # not so easy, looks for variable which changes from one solution
    # to another
    unstables = rqlst.get_variable_indices()
    basedescr = []
    todetermine = []
    for i in range(len(rqlst.children[0].selection)):
        ttype = _selection_idx_type(i, rqlst, args)
        if ttype is None or ttype == 'Any':
Exemplo n.º 9
0
class Subscriber(object):
    def __init__(self, ioloop, address):
        self.address = address
        self.dispatch_table = {}
        self.ioloop = ioloop

        def callback():
            s = ctx.socket(zmq.SUB)
            self.stream = zmq.eventloop.zmqstream.ZMQStream(s, io_loop=ioloop)
            self.stream.on_recv(self.dispatch)
            self.stream.connect(self.address)
            self.debug('start subscriber on %s', self.address)

        ioloop.add_callback(callback)

    def dispatch(self, msg):
        try:
            f = self.dispatch_table[msg[0]]
        except KeyError:
            return
        f(msg)

    def subscribe(self, topic, callback):
        self.dispatch_table[topic] = callback
        self.ioloop.add_callback(
            lambda: self.stream.setsockopt(zmq.SUBSCRIBE, topic))


set_log_methods(Publisher, getLogger('cubicweb.zmq.pub'))
set_log_methods(Subscriber, getLogger('cubicweb.zmq.sub'))
Exemplo n.º 10
0
        else:
            self.warning('the edited data seems inconsistent')
            path = 'view'
        # pick up the correction edition view
        if form.get('__form_id'):
            newparams['vid'] = form['__form_id']
        # re-insert copy redirection parameters
        for redirectparam in NAV_FORM_PARAMETERS:
            if redirectparam in form:
                newparams[redirectparam] = form[redirectparam]
        raise Redirect(self._cw.build_url(path, **newparams))

    def _redirect(self, newparams):
        """Raise a redirect. We use __redirectpath if it specified, else we
        return to the home page.
        """
        if '__redirectpath' in self._cw.form:
            # if redirect path was explicitly specified in the form, use it
            path = self._cw.form['__redirectpath']
            url = self._cw.build_url(path)
            url = append_url_params(url, self._cw.form.get('__redirectparams'))
        else:
            url = self._cw.base_url()
        # The newparams must update the params in all cases
        url = self._cw.rebuild_url(url, **newparams)
        raise Redirect(url)


from cubicweb import set_log_methods
set_log_methods(Controller, LOGGER)
Exemplo n.º 11
0
            self.hm.call_hooks('after_add_relation',
                               cnx,
                               rtype=rtype,
                               eids_from_to=source_relations)

    def glob_delete_relation(self, cnx, subject, rtype, object):
        """delete a relation from the repository"""
        if server.DEBUG & server.DBG_REPO:
            print('DELETE relation', subject, rtype, object)
        source = self.system_source
        self.hm.call_hooks('before_delete_relation',
                           cnx,
                           eidfrom=subject,
                           rtype=rtype,
                           eidto=object)
        source.delete_relation(cnx, subject, rtype, object)
        rschema = self.schema.rschema(rtype)
        cnx.update_rel_cache_del(subject, rtype, object, rschema.symmetric)
        self.hm.call_hooks('after_delete_relation',
                           cnx,
                           eidfrom=subject,
                           rtype=rtype,
                           eidto=object)

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


set_log_methods(Repository, getLogger('cubicweb.repository'))