Ejemplo n.º 1
0
 def test_no_autosave_saves_atime_without_save(self):
     so = SessionObject({}, auto=False)
     so['foo'] = 'bar'
     so.persist()
     session = get_session(id=so.id)
     assert '_accessed_time' in session
     assert 'foo' not in session  # because we didn't save()
Ejemplo n.º 2
0
 def test_auto_save_saves_without_save(self):
     so = SessionObject({}, auto=True)
     so['foo'] = 'bar'
     # look ma, no save()!
     so.persist()
     session = get_session(id=so.id)
     assert 'foo' in session
Ejemplo n.º 3
0
 def test_auto_save_saves_without_save(self):
     so = SessionObject({}, auto=True)
     so["foo"] = "bar"
     # look ma, no save()!
     so.persist()
     session = get_session(id=so.id)
     assert "foo" in session
Ejemplo n.º 4
0
 def test_auto_save_saves_without_save(self):
     so = SessionObject({}, auto=True)
     so['foo'] = 'bar'
     # look ma, no save()!
     so.persist()
     session = get_session(id=so.id)
     assert 'foo' in session
Ejemplo n.º 5
0
 def test_no_autosave_saves_atime_without_save(self):
     so = SessionObject({}, auto=False)
     so["foo"] = "bar"
     so.persist()
     session = get_session(id=so.id)
     assert "_accessed_time" in session
     assert "foo" not in session  # because we didn't save()
Ejemplo n.º 6
0
def current_participant(request, dbsession, experiment, allow_create=True):
    """Get the current Participant or create a new one."""
    session = SessionObject(request.environ,
                            **coerce_session_params({'type': 'cookie',
                                                     'cookie_expires': 7776000,
                                                     'key': 'experiment.%s' % (experiment.external_id),
                                                     'encrypt_key':
                                                     get_config_setting(request, 'beaker.session.encrypt_key'),
                                                     'validate_key':
                                                     get_config_setting(request, 'beaker.session.validate_key'),
                                                     'auto': True}))
    if 'pid' in session:
        participant = dbsession.query(Participant).filter(and_(Participant.id == session['pid'],
                                                               Participant.experiment_id == experiment.id)).first()
    else:
        participant = None
    if participant is None:
        if allow_create:
            participant = Participant(experiment_id=experiment.id,
                                      completed=False)
            participant['current'] = experiment.start.id
            participant['answered'] = []
            dbsession.add(participant)
            dbsession.flush()
        else:
            return None
    session['pid'] = participant.id
    session.persist()
    request.response.headerlist.append(('Set-Cookie', session.__dict__['_headers']['cookie_out']))
    return participant
Ejemplo n.º 7
0
def completed(request):
    dbsession = DBSession
    with transaction.manager:
        experiment = dbsession.query(Experiment).filter(Experiment.external_id == request.matchdict['ueid']).first()
        if experiment is None:
            raise HTTPNotFound()
        if experiment.status in ['paused', 'completed']:
            raise HTTPFound(request.route_url('experiment.unavailable', ueid=experiment.external_id))
        participant = current_participant(request, dbsession, experiment, allow_create=False)
        if participant is None:
            if experiment.status == 'develop':
                raise HTTPFound(request.route_url('experiment.test', ueid=experiment.external_id))
            else:
                raise HTTPFound(request.route_url('experiment.run', ueid=experiment.external_id))
        participant.completed = True
    dbsession.add(experiment)
    dbsession.add(participant)
    if experiment.status == 'develop':
        session = SessionObject(request.environ,
                                **coerce_session_params({'type': 'cookie',
                                                         'cookie_expires': 7776000,
                                                         'key': 'experiment.%s' % (experiment.external_id),
                                                         'encrypt_key':
                                                         get_config_setting(request, 'beaker.session.encrypt_key'),
                                                         'validate_key':
                                                         get_config_setting(request, 'beaker.session.validate_key'),
                                                         'auto': True}))
        session['pid'] = -1
        session.persist()
        request.response.headerlist.append(('Set-Cookie', session.__dict__['_headers']['cookie_out']))
    return {'experiment': experiment,
            'participant': participant}
Ejemplo n.º 8
0
 def test_no_autosave_saves_atime_without_save(self):
     so = SessionObject({}, auto=False)
     so['foo'] = 'bar'
     so.persist()
     session = get_session(id=so.id)
     assert '_accessed_time' in session
     assert 'foo' not in session  # because we didn't save()
Ejemplo n.º 9
0
 def test_no_autosave_saves_with_save(self):
     so = SessionObject({}, auto=False)
     so['foo'] = 'bar'
     so.save()
     so.persist()
     session = get_session(id=so.id)
     assert '_accessed_time' in session
     assert 'foo' in session
Ejemplo n.º 10
0
 def test_accessed_time_off_saves_atime_when_saving(self):
     so = SessionObject({}, save_accessed_time=False)
     atime = so['_accessed_time']
     so['foo'] = 'bar'
     so.save()
     so.persist()
     session = get_session(id=so.id, save_accessed_time=False)
     assert 'foo' in session
     assert '_accessed_time' in session
     self.assertEqual(session.last_accessed, atime)
Ejemplo n.º 11
0
 def __init__(self, request):
     SessionObject.__init__(self, request.environ, **self._options)
     def session_callback(request, response):
         exception = getattr(request, 'exception', None)
         if (exception is None or self._cookie_on_exception
             and self.accessed()):
             self.persist()
             headers = self.__dict__['_headers']
             if headers['set_cookie'] and headers['cookie_out']:
                 response.headerlist.append(
                     ('Set-Cookie', headers['cookie_out']))
     request.add_response_callback(session_callback)
Ejemplo n.º 12
0
        def __init__(self, request):
            SessionObject.__init__(self, request.environ, **self._options)

            def session_callback(request, response):
                exception = getattr(request, "exception", None)
                if exception is None or self._cookie_on_exception and self.accessed():
                    self.persist()
                    headers = self.__dict__["_headers"]
                    if headers["set_cookie"] and headers["cookie_out"]:
                        response.headerlist.append(("Set-Cookie", headers["cookie_out"]))

            request.add_response_callback(session_callback)
Ejemplo n.º 13
0
        def __init__(self, request):
            SessionObject.__init__(self, request.environ, **self._options)

            def session_callback(request, response):
                exception = getattr(request, 'exception', None)
                if (exception is None
                        or self._cookie_on_exception and self.accessed()):
                    self.persist()
                    headers = self.__dict__['_headers']
                    if headers['set_cookie'] and headers['cookie_out']:
                        response.headerlist.append(
                            ('Set-Cookie', headers['cookie_out']))

            request.add_response_callback(session_callback)
Ejemplo n.º 14
0
    def test_no_autosave_saves_with_delete(self):
        req = {'cookie': {'beaker.session.id': 123}}

        so = SessionObject(req, auto=False)
        so['foo'] = 'bar'
        so.save()
        so.persist()
        session = get_session(id=so.id)
        assert 'foo' in session

        so2 = SessionObject(req, auto=False)
        so2.delete()
        so2.persist()
        session = get_session(id=so2.id)
        assert 'foo' not in session
Ejemplo n.º 15
0
    def __call__(self, environ, start_response):
        """
        This function's implementation is taken directly from Beaker,
        with HTTPS detection added. When accessed over HTTPS, force
        setting cookie's secure flag.

        The only difference from that original code is that we switch
        the secure option on and off depending on the URL scheme (first
        two lines). To avoid concurrency issues, we use a local options
        variable.
        """
        options = dict(self.options)
        options["secure"] = environ['wsgi.url_scheme'] == 'https'

        session = SessionObject(environ, **options)
        if environ.get('paste.registry'):
            if environ['paste.registry'].reglist:
                environ['paste.registry'].register(self.session, session)
        environ[self.environ_key] = session
        environ['beaker.get_session'] = self._get_session

        if 'paste.testing_variables' in environ and 'webtest_varname' in options:
            environ['paste.testing_variables'][
                options['webtest_varname']] = session

        def session_start_response(status, headers, exc_info=None):
            if session.accessed():
                session.persist()
                if session.__dict__['_headers']['set_cookie']:
                    cookie = session.__dict__['_headers']['cookie_out']
                    if cookie:
                        headers.append(('Set-cookie', cookie))
            return start_response(status, headers, exc_info)

        return self.wrap_app(environ, session_start_response)
Ejemplo n.º 16
0
 def session(self):
     """Create and return the session object
     
     This also adds a response callback, which ensures that the
     session is written out, and the appropriate cookie's are
     set if necessary on the response object.
     
     """
     exception_abort = self.registry.session_exception
     sess_opts = self.registry.session_options
     if not sess_opts:
         raise Exception("Can't use the session without configuring sessions")
     session = SessionObject(self.environ, **sess_opts)
     def session_callback(request, response):
         exception = getattr(request, 'exception', None)
         if  exception is not None and exception_abort:
             return None
         if session.accessed():
             session.persist()
             if session.__dict__['_headers']['set_cookie']:
                 cookie = session.__dict__['_headers']['cookie_out']
                 if cookie:
                     response.headerlist.append(('Set-cookie', cookie))
     self._sess_callback = session_callback
     self.add_response_callback(session_callback)
     return session
Ejemplo n.º 17
0
def create_fake_env():
    registry = Registry()
    registry.prepare()
    registry.register(session, SessionObject({}))
    registry.register(request, Request.blank('/bootstrap'))
    request.identity = {}

    return session, request
 def restore_session(self, environ):
     '''Given a wsgi environment it reconstruct a session object
     :param environ: wsgi environment
     :return: session object
     '''
     session = SessionObject(environ, **self.options)
     environ[self.environ_key] = session
     environ['beaker.get_session'] = self._get_session
     return Session({}, use_cookies=True, **self.options)
Ejemplo n.º 19
0
    def test_accessed_time_off_doesnt_save_without_save(self):
        req = {'cookie': {'beaker.session.id': 123}}
        so = SessionObject(req, save_accessed_time=False)
        so.persist()  # so we can do a set on a non-new session

        so2 = SessionObject(req, save_accessed_time=False)
        so2['foo'] = 'bar'
        # no save()
        so2.persist()

        session = get_session(id=so.id, save_accessed_time=False)
        assert 'foo' not in session
Ejemplo n.º 20
0
    def test_accessed_time_off_doesnt_save_without_save(self):
        req = {"cookie": {"beaker.session.id": 123}}
        so = SessionObject(req, save_accessed_time=False)
        so.persist()  # so we can do a set on a non-new session

        so2 = SessionObject(req, save_accessed_time=False)
        so2["foo"] = "bar"
        # no save()
        so2.persist()

        session = get_session(id=so.id, save_accessed_time=False)
        assert "foo" not in session
Ejemplo n.º 21
0
    def _respond(cls, request):
        try:
            path_response = cls.__routes.match(request.path_info)
            if path_response[0] is None:
                raise exc.HTTPNotFound()

            endpoint = path_response[0]
            session = SessionObject(
                request.environ, **cls.__get_session_config())

            try:
                method = endpoint(request.method)
                result = method(
                    _Request(
                        session=session,
                        route_params=path_response[1],
                        path_for=cls.__routes.path_for,
                        raw=request
                    )
                )

            except Exception as e:
                raise exc.HTTPServerError()

            response = webob.Response()

            if session.accessed():
                if not session.dirty():
                    session.save()
                session.persist()
                cookie = session.__dict__['_headers']['cookie_out'] if \
                    session.__dict__['_headers']['set_cookie'] else None
                if cookie:
                    response.headers.add('Set-Cookie', cookie)

            if cls.__config['show_x_powered_by']:
                response.headers.add(
                    'X-Powered-By', 'Lulu version %s' % _VERSION)

            if isinstance(result, basestring):
                response.text = result
                response.charset = 'utf8'
            elif type(result) is dict:
                response.content_type = result['content_type'] if \
                    'content_type' in result.keys() else 'text/html'
                response.body = result['body']

            return response
        except exc.HTTPError as e:
            return e
Ejemplo n.º 22
0
 def test_no_autosave_saves_with_save(self):
     so = SessionObject({}, auto=False)
     so['foo'] = 'bar'
     so.save()
     so.persist()
     session = get_session(id=so.id)
     assert '_accessed_time' in session
     assert 'foo' in session
Ejemplo n.º 23
0
 def test_no_autosave_saves_with_save(self):
     so = SessionObject({}, auto=False)
     so["foo"] = "bar"
     so.save()
     so.persist()
     session = get_session(id=so.id)
     assert "_accessed_time" in session
     assert "foo" in session
Ejemplo n.º 24
0
def _init_stack(config=None, environ=None):
    if not config:
        config = pylons.test.pylonsapp.config
    if not environ:
        environ = {}
    pylons.url._push_object(URLGenerator(config['routes.map'], environ or {}))
    pylons.app_globals._push_object(config['pylons.app_globals'])
    pylons.config._push_object(config)
    pylons.tmpl_context._push_object(ContextObj())
    # Initialize a translator for tests that utilize i18n
    translator = _get_translator(pylons.config.get('lang'))
    pylons.translator._push_object(translator)
    pylons.session._push_object(SessionObject(environ or {}))
    pylons.request._push_object(webob.Request.blank('', environ=environ))
Ejemplo n.º 25
0
def fake_request(pylons_config,
                 server_name='mediacore.example',
                 language='en',
                 method='GET',
                 request_uri='/',
                 post_vars=None):
    app_globals = pylons_config['pylons.app_globals']
    pylons.app_globals._push_object(app_globals)

    if post_vars and method.upper() != 'POST':
        raise ValueError(
            'You must not specify post_vars for request method %r' % method)
    wsgi_environ = create_wsgi_environ('http://%s%s' %
                                       (server_name, request_uri),
                                       method.upper(),
                                       request_body=post_vars)
    request = Request(wsgi_environ, charset='utf-8')
    request.language = language
    request.settings = app_globals.settings
    pylons.request._push_object(request)
    response = Response(content_type='application/xml', charset='utf-8')
    pylons.response._push_object(response)

    session = SessionObject(wsgi_environ)
    pylons.session._push_object(session)

    routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ)
    pylons.url._push_object(routes_url)

    # Use ContextObj() when we get rid of 'pylons.strict_tmpl_context=False' in
    # mediacore.lib.environment
    tmpl_context = AttribSafeContextObj()
    tmpl_context.paginators = Bunch()
    pylons.tmpl_context._push_object(tmpl_context)
    # some parts of Pylons (e.g. Pylons.controllers.core.WSGIController)
    # use the '.c' alias instead.
    pylons.c = pylons.tmpl_context

    paste_registry = Registry()
    paste_registry.prepare()
    engines = create_tw_engine_manager(app_globals)
    host_framework = PylonsHostFramework(engines=engines)
    paste_registry.register(tw.framework, host_framework)
    setup_translator(language=language, registry=paste_registry)

    wsgi_environ.update({
        'pylons.pylons': pylons,
        'paste.registry': paste_registry,
    })
    return request
Ejemplo n.º 26
0
def fake_request(pylons_config, server_name='mediadrop.example', language='en',
                 method='GET', request_uri='/', post_vars=None):
    app_globals = pylons_config['pylons.app_globals']
    pylons.app_globals._push_object(app_globals)
    
    if post_vars and method.upper() != 'POST':
        raise ValueError('You must not specify post_vars for request method %r' % method)
    wsgi_environ = create_wsgi_environ('http://%s%s' % (server_name, request_uri),
        method.upper(), request_body=post_vars)
    request = Request(wsgi_environ, charset='utf-8')
    request.language = language
    request.settings = app_globals.settings
    pylons.request._push_object(request)
    response = Response(content_type='application/xml', charset='utf-8')
    pylons.response._push_object(response)
    
    session = SessionObject(wsgi_environ)
    pylons.session._push_object(session)

    routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ)
    pylons.url._push_object(routes_url)

    # TODO: Use ContextObj() for Pylons 0.10
    tmpl_context = AttribSafeContextObj()
    tmpl_context.paginators = Bunch()
    pylons.tmpl_context._push_object(tmpl_context)
    # some parts of Pylons (e.g. Pylons.controllers.core.WSGIController)
    # use the '.c' alias instead.
    pylons.c = pylons.tmpl_context
    
    paste_registry = Registry()
    paste_registry.prepare()
    engines = create_tw_engine_manager(app_globals)
    host_framework = PylonsHostFramework(engines=engines)
    paste_registry.register(tw.framework, host_framework)
    
    mediacore_i18n_path = os.path.join(os.path.dirname(mediacore.__file__), 'i18n')
    translator = Translator(language, dict(mediacore=mediacore_i18n_path))
    # not sure why but sometimes pylons.translator is not a StackedObjectProxy
    # but just a regular Translator.
    if not hasattr(pylons.translator, '_push_object'):
        pylons.translator = StackedObjectProxy()
    paste_registry.replace(pylons.translator, translator)
    
    wsgi_environ.update({
        'pylons.pylons': pylons,
        'paste.registry': paste_registry,
    })
    return request
Ejemplo n.º 27
0
 def test_accessed_time_off_saves_atime_when_saving(self):
     so = SessionObject({}, save_accessed_time=False)
     atime = so['_accessed_time']
     so['foo'] = 'bar'
     so.save()
     so.persist()
     session = get_session(id=so.id, save_accessed_time=False)
     assert 'foo' in session
     assert '_accessed_time' in session
     self.assertEqual(session.last_accessed, atime)
Ejemplo n.º 28
0
 def test_accessed_time_off_saves_atime_when_saving(self):
     so = SessionObject({}, save_accessed_time=False)
     atime = so["_accessed_time"]
     so["foo"] = "bar"
     so.save()
     so.persist()
     session = get_session(id=so.id, save_accessed_time=False)
     assert "foo" in session
     assert "_accessed_time" in session
     self.assertEqual(session.last_accessed, atime)
Ejemplo n.º 29
0
    def __call__(self, environ, start_response):
        session = SessionObject(environ, **self.options)
        if environ.get('paste.registry'):
            if environ['paste.registry'].reglist:
                environ['paste.registry'].register(self.session, session)
        environ[self.environ_key] = session
        environ['beaker.get_session'] = self._get_session

        def session_start_response(status, headers, exc_info=None):
            if session.__dict__['_sess'] is not None:
                if session.__dict__['_headers']['set_cookie']:
                    cookie = session.__dict__['_headers']['cookie_out']
                    if cookie:
                        headers.append(('Set-cookie', cookie))
            return start_response(status, headers, exc_info)

        return self.wrap_app(environ, session_start_response)
Ejemplo n.º 30
0
    def __call__(self, environ, start_response):
        session = SessionObject(environ, **self.session_options)

        environ['beaker.session'] = session
        environ['beaker.get_session'] = self._get_session

        def session_start_response(status, headers, exc_info=None):
            if session.accessed():
                session.persist()
                if session.__dict__['_headers']['set_cookie']:
                    cookie = session.__dict__['_headers']['cookie_out']
                    if cookie:
                        headers.append(('Set-cookie', cookie))

            return start_response(status, headers, exc_info)

        return super(BottleExt, self).__call__(environ, session_start_response)
Ejemplo n.º 31
0
    def test_accessed_time_off_doesnt_save_without_save(self):
        req = {'cookie': {'beaker.session.id': 123}}
        so = SessionObject(req, save_accessed_time=False)
        so.persist()  # so we can do a set on a non-new session

        so2 = SessionObject(req, save_accessed_time=False)
        so2['foo'] = 'bar'
        # no save()
        so2.persist()

        session = get_session(id=so.id, save_accessed_time=False)
        assert 'foo' not in session
Ejemplo n.º 32
0
    def __call__(self, controller, environ, context):
        context.session = session = SessionObject(environ, **self.options)
        environ['beaker.session'] = session
        environ['beaker.get_session'] = self._get_session

        if 'paste.testing_variables' in environ:
            environ['paste.testing_variables']['session'] = session

        response = self.next_handler(controller, environ, context)

        if session.accessed():
            session.persist()
            session_headers = session.__dict__['_headers']
            if session_headers['set_cookie']:
                cookie = session_headers['cookie_out']
                if cookie:
                    response.headers.extend((('Set-cookie', cookie), ))

        return response
Ejemplo n.º 33
0
    def __call__(self, environ, start_response):
        session = SessionObject(environ, **self.options)
        if environ.get('paste.registry'):
            if environ['paste.registry'].reglist:
                environ['paste.registry'].register(self.session, session)
        environ[self.environ_key] = session
        environ['beaker.get_session'] = self._get_session

        if 'paste.testing_variables' in environ and 'webtest_varname' in self.options:
            environ['paste.testing_variables'][self.options['webtest_varname']] = session

        def session_start_response(status, headers, exc_info = None):
            if session.accessed():
                session.persist()
                if session.__dict__['_headers']['set_cookie']:
                    cookie = session.__dict__['_headers']['cookie_out']
                    if cookie:
                        headers.append(('Set-cookie', cookie))
            return start_response(status, headers, exc_info)
        return self.wrap_app(environ, session_start_response)
Ejemplo n.º 34
0
    def __call__(self, environ, start_response):
        session = SessionObject(environ, **self.options)
        if environ.get("paste.registry"):
            if environ["paste.registry"].reglist:
                environ["paste.registry"].register(self.session, session)
        environ[self.environ_key] = session
        environ["beaker.get_session"] = self._get_session

        if "paste.testing_variables" in environ and "webtest_varname" in self.options:
            environ["paste.testing_variables"][
                self.options["webtest_varname"]] = session

        def session_start_response(status, headers, exc_info=None):
            if session.accessed():
                session.persist()
                if session.__dict__["_headers"]["set_cookie"]:
                    cookie = session.__dict__["_headers"]["cookie_out"]
                    if cookie:
                        headers.append(("Set-cookie", cookie))
            return start_response(status, headers, exc_info)

        return self.wrap_app(environ, session_start_response)
Ejemplo n.º 35
0
    def process_request(self, request, *args):
        session_id = request.headers.get(FallbackSessionMiddleware.HEADER_NAME,
                                         None)
        session = SessionObject(request.env, id=session_id, **self.options)

        request.env[self.environ_key] = session
Ejemplo n.º 36
0
    def test_no_autosave_saves_with_delete(self):
        req = {'cookie': {'beaker.session.id': 123}}

        so = SessionObject(req, auto=False)
        so['foo'] = 'bar'
        so.save()
        so.persist()
        session = get_session(id=so.id)
        assert 'foo' in session

        so2 = SessionObject(req, auto=False)
        so2.delete()
        so2.persist()
        session = get_session(id=so2.id)
        assert 'foo' not in session
Ejemplo n.º 37
0
 def __init__(self, environ, **params):
     SessionObject.__init__(self, environ, **params)
Ejemplo n.º 38
0
 def __init__(self, environ, **params):
     SessionObject.__init__(self, environ, **params)
Ejemplo n.º 39
0
def bootstrap(command, conf, vars):
    """Place any commands to setup bq here"""

    # <websetup.bootstrap.before.auth
    from sqlalchemy.exc import IntegrityError
    from  bq.data_service.model import Taggable, Tag, BQUser, ModuleExecution

    registry = Registry()
    registry.prepare()
    registry.register(session, SessionObject({}))
    registry.register(request, Request.blank('/bootstrap'))
    request.identity = {}

    log.info('BEGIN boostrap')
    try:
        initial_mex = ModuleExecution(mex_id = False, owner_id = False)
        initial_mex.mex = initial_mex
        initial_mex.name = "initialization"
        initial_mex.type = "initialization"
        initial_mex.hidden = True
        model.DBSession.add(initial_mex)
        model.DBSession.flush()

        admin = model.User(
            user_name = u"admin",
            display_name = config.get('bisque.admin_display_name', u'Bisque admin'))
        admin._email_address = config.get('bisque.admin_email', u'*****@*****.**')
        admin.password = u'admin'
        #    password = u'admin')
        #admin.password = u'admin'
        model.DBSession.add(admin)

        for g in [ u'admins', u'managers' ] :
            group = model.Group()
            group.group_name = g
            group.display_name = u'Administrators Group'
            group.users.append(admin)
            model.DBSession.add(group)

        permission = model.Permission()
        permission.permission_name = u'root'
        permission.description = u'This permission give an administrative right to the bearer'
        permission.groups.append(group)
        model.DBSession.add(permission)
        #model.DBSession.flush()
        # This commit will setup the BQUser also
        transaction.commit()

    except IntegrityError:
        print 'Warning, there was a problem adding your auth data, it may have already been added:'
        #import traceback
        #print traceback.format_exc()
        transaction.abort()
        print 'Continuing with bootstrapping...'


    try:
        ######
        #
        #from bq.data_service.model import UniqueName
        initial_mex = model.DBSession.query(ModuleExecution).first()
        session['mex_id'] = initial_mex.id
        #request.identity['bisque.mex_id'] = initial_mex.id


        admin = model.DBSession.query(BQUser).filter_by(resource_name = 'admin').first()
        admin.mex_id = initial_mex.id
        initial_mex.owner = admin
        session['user'] = admin


        system = model.DBSession.query(Taggable).filter_by (resource_type='system').first()
        if system is None:
            system_prefs = defaults_path('preferences.xml.default')
            if os.path.exists(system_prefs):
                with open (system_prefs) as f:
                    system = bisquik2db (f)
                    system.permission = 'published'
            else:
                print( "Couldn't find %s: using minimal default preferences" % system_prefs)
                system = Taggable(resource_type = 'system')
                version = Tag(parent = system)
                version.name ='version'
                version.value  = __VERSION__
                prefs = Tag(parent = system)
                prefs.name = 'Preferences'
            model.DBSession.add(system)
            transaction.commit()



    except IntegrityError:
        log.exception ( 'Warning, there was a problem adding your system object, it may have already been added:')
        #import traceback
        #print traceback.format_exc()
        transaction.abort()
        log.warning ( 'Continuing with bootstrapping...' )

    log.info('END boostrap')