Пример #1
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    config = Configurator(settings=settings)
    settings = config.get_settings()
    settings.update(yaml.load(file(settings.get("app.cfg"))))

    add_mako_renderer(config, ".html")
    add_mako_renderer(config, ".js")

    engine = engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)
    dbreflection.init(engine)

    config.set_authorization_policy(ACLAuthorizationPolicy())

    config.add_request_method(
        _create_get_user_from_request(settings),
        name="user",
        property=True
    )

    authtkt_authentication_policy = AuthTktAuthenticationPolicy(
        settings.get('authtkt')['secret'],
        cookie_name=settings.get('authtkt')['cookie_name'],
        hashalg='sha512'
    )

    remote_user_authentication_policy = RemoteUserAuthenticationPolicy()
    policies = [remote_user_authentication_policy, authtkt_authentication_policy]
    authentication_policy = MultiAuthenticationPolicy(policies)
    config.set_authentication_policy(authentication_policy)

    config.include('pyramid_mako')
    config.include(pyramid_tm.includeme)

    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')
    config.add_route('viewer', '/viewer.js')
    config.add_route('image_proxy', '/img/{type}/{id}')
    config.add_route('pdf_proxy', '/pdf/{type}/{id}.pdf')

    # historic parcels
    config.add_route('historic_parcel_get', '/historic_parcel/{id}')
    config.add_route('historic_parcel', '/historic_parcel')
    config.add_route('historic_parcel_doc', '/historic_parcel_doc')

    # print proxy routes
    config.add_route('printproxy', '/printproxy')
    config.add_route('printproxy_info', '/printproxy/info.json')
    config.add_route('printproxy_create', '/printproxy/create.json')
    config.add_route('printproxy_get', '/printproxy/{file}.printout')

    # mutation
    config.add_route('mutation_list', '/mutation/list')

    config.scan()
    return config.make_wsgi_app()
Пример #2
0
def initialized(ev):
    PTAH = ptah.get_settings(ptah.CFG_ID_PTAH, ev.registry)

    # mail
    PTAH['Mailer'] = DummyMailer()
    PTAH['full_email_address'] = formataddr(
        (PTAH['email_from_name'], PTAH['email_from_address']))

    # sqla
    SQLA = ptah.get_settings(ptah.CFG_ID_SQLA, ev.registry)
    url = SQLA['url']
    if url:
        engine_args = {}
        if SQLA['cache']:
            cache = {}
            engine_args['execution_options'] = \
                {'compiled_cache': cache}
            SQLA['sqlalchemy_cache'] = cache
        try:
            engine = sqlahelper.get_engine()
        except: # pragma: no cover
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': url}, 'sqlalchemy.', **engine_args)
            sqlahelper.add_engine(engine)

    # ptah manage
    if PTAH['manage']:
        ev.config.add_route(
            'ptah-manage', '/ptah-manage/*traverse',
            factory=ptah.manage.PtahManageRoute, use_global_views=True)
        ptah.manage.set_access_manager(
            ptah.manage.PtahAccessManager())
Пример #3
0
def setUpCommon():
    import c2cgeoportal
    c2cgeoportal.schema = 'main'
    c2cgeoportal.srid = 21781
    c2cgeoportal.caching.init_region({'backend': 'dogpile.cache.memory'})

    # if test.in does not exist (because the z3c.recipe.filetemplate
    # part hasn't been executed) then db_url is None
    if db_url is None:  # pragma: nocover
        return

    # verify that we have a working database connection before going
    # forward
    from sqlalchemy import create_engine
    from sqlalchemy.exc import OperationalError
    engine = create_engine(db_url)
    try:
        engine.connect()
    except OperationalError:  # pragma: nocover
        return

    import sqlahelper
    sqlahelper.add_engine(engine)

    from c2cgeoportal.models import Base
    Base.metadata.create_all()
Пример #4
0
def create_engine(create_engine_dotted, dburl):
    if create_engine_dotted:
        return import_symbol(create_engine_dotted)(dburl)
    else:
        engine = sa.create_engine(dburl)
        sqlahelper.add_engine(engine)
        return engine
Пример #5
0
 def test1(self):
     import transaction
     Base = sqlahelper.get_base()
     class Person(Base):
         __tablename__ = "people"
         id = sa.Column(sa.Integer, primary_key=True)
         first_name = sa.Column(sa.Unicode(100), nullable=False)
         last_name = sa.Column(sa.Unicode(100), nullable=False)
     engine = sa.create_engine(self.db1.url)
     sqlahelper.add_engine(engine)
     Base.metadata.create_all()
     fred = Person(id=1, first_name=u"Fred", last_name=u"Flintstone")
     wilma = Person(id=2, first_name=u"Wilma", last_name=u"Flintstone")
     barney = Person(id=3, first_name=u"Barney", last_name=u"Rubble")
     betty = Person(id=4, first_name=u"Betty", last_name=u"Rubble")
     Session = sqlahelper.get_session()
     sess = Session()
     sess.add_all([fred, wilma, barney, betty])
     transaction.commit()
     sess.expunge_all()
     del fred, wilma, barney, betty
     # Can we get back a record?
     barney2 = sess.query(Person).get(3)
     self.assertEqual(barney2.id, 3)
     self.assertEqual(barney2.first_name, u"Barney")
     self.assertEqual(barney2.last_name, u"Rubble")
     sa.select([Person.first_name])
     # Can we iterate the first names in reverse alphabetical order?
     q = sess.query(Person.first_name).order_by(Person.first_name.desc())
     result = [x.first_name for x in q]
     control = [u"Wilma", u"Fred", u"Betty", u"Barney"]
     self.assertEqual(result, control)
Пример #6
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    engine = engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)

    dbreflection.init(engine)

    settings.setdefault('mako.directories', 'historic_cadastre:templates')
    settings.setdefault('reload_templates', True)

    config = Configurator(settings=settings)

    config.add_renderer('.html', mako_renderer_factory)
    config.add_renderer('.js', mako_renderer_factory)

    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')
    config.add_route('viewer', '/viewer.js')
    config.add_route('image_proxy', '/img/{type}/{id}')
    config.add_route('pdf_proxy', '/pdf/{type}/{id}')

    # print proxy routes
    config.add_route('printproxy', '/printproxy')
    config.add_route('printproxy_info', '/printproxy/info.json')
    config.add_route('printproxy_create', '/printproxy/create.json')
    config.add_route('printproxy_get', '/printproxy/{file}.printout')

    # mutation
    config.add_route('mutation_list', '/mutation/list')

    config.scan()
    return config.make_wsgi_app()
Пример #7
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    for p in ['rte', 'enedis', 'ogm']:
        PROFILES[settings['profile.%s' % p]] = p

    session_factory = session_factory_from_settings(settings)
    config = Configurator(settings=settings, session_factory=session_factory)

    config.include('pyramid_mako')

    # initialize database
    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)

    # add the "geojson" renderer
    config.add_renderer(name='csv', factory='cables.renderers.CSVRenderer')

    # add routes to the entry view class
    config.add_route('export_zonessensibles', '/export/zonessensibles')
    config.add_route('export_communes', '/export/communes')
    config.add_route('export_departements', '/export/departements')
    config.add_route('profile', '/profile')
    config.scan()

    # add the static view (for static resources)
    config.add_static_view('static', 'cables:static')

    return config.make_wsgi_app()
Пример #8
0
def setUpCommon():
    import c2cgeoportal
    c2cgeoportal.schema = 'main'
    c2cgeoportal.srid = 21781
    c2cgeoportal.caching.init_region({'backend': 'dogpile.cache.memory'})

    # if test.in does not exist (because the z3c.recipe.filetemplate
    # part hasn't been executed) then db_url is None
    if db_url is None:  # pragma: nocover
        return

    # verify that we have a working database connection before going
    # forward
    from sqlalchemy import create_engine
    from sqlalchemy.exc import OperationalError
    engine = create_engine(db_url)
    try:
        engine.connect()
    except OperationalError:  # pragma: nocover
        return

    import sqlahelper
    sqlahelper.add_engine(engine)

    from c2cgeoportal.models import Base
    Base.metadata.create_all()
Пример #9
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    settings = config.get_settings()

    settings.update(yaml.load(file(settings.get("app.cfg"))))

    add_mako_renderer(config, ".html")
    add_mako_renderer(config, ".js")

    config.include("pyramid_mako")

    engine = engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)

    config.include(pyramid_tm.includeme)

    dbreflection.init(engine)

    config.include('.routes')

    config.scan()

    return config.make_wsgi_app()
Пример #10
0
 def test1(self):
     import transaction
     Base = sqlahelper.get_base()
     class Person(Base):
         __tablename__ = "people"
         id = sa.Column(sa.Integer, primary_key=True)
         first_name = sa.Column(sa.Unicode(100), nullable=False)
         last_name = sa.Column(sa.Unicode(100), nullable=False)
     engine = sa.create_engine(self.db1.url)
     sqlahelper.add_engine(engine)
     Base.metadata.create_all()
     fred = Person(id=1, first_name=u"Fred", last_name=u"Flintstone")
     wilma = Person(id=2, first_name=u"Wilma", last_name=u"Flintstone")
     barney = Person(id=3, first_name=u"Barney", last_name=u"Rubble")
     betty = Person(id=4, first_name=u"Betty", last_name=u"Rubble")
     Session = sqlahelper.get_session()
     sess = Session()
     sess.add_all([fred, wilma, barney, betty])
     transaction.commit()
     sess.expunge_all()
     del fred, wilma, barney, betty
     # Can we get back a record?
     barney2 = sess.query(Person).get(3)
     self.assertEqual(barney2.id, 3)
     self.assertEqual(barney2.first_name, u"Barney")
     self.assertEqual(barney2.last_name, u"Rubble")
     sa.select([Person.first_name])
     # Can we iterate the first names in reverse alphabetical order?
     q = sess.query(Person.first_name).order_by(Person.first_name.desc())
     result = [x.first_name for x in q]
     control = [u"Wilma", u"Fred", u"Betty", u"Barney"]
     self.assertEqual(result, control)
Пример #11
0
 def test_add_engine_twice(self):
     db1 = sa.create_engine(self.db1.url)
     db2 = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(db1)
     self.assertIs(sqlahelper.get_session().bind, db1)
     sqlahelper.add_engine(db2)
     self.assertIs(sqlahelper.get_session().bind, db2)
     self.assertIs(sqlahelper.get_session().bind, sqlahelper.sessions.default.registry.registry.value.bind)
Пример #12
0
    def setUp(self):
        try:
            engine = sqlahelper.get_engine()
        except:  # pragma: no cover
            engine = sqlalchemy.engine_from_config({"sqlalchemy.url": "sqlite://"})
            sqlahelper.add_engine(engine)

        self._setup_pyramid()
Пример #13
0
 def test_add_engine_twice(self):
     db1 = sa.create_engine(self.db1.url)
     db2 = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(db1)
     self.assertIs(sqlahelper.get_session().bind, db1)
     sqlahelper.add_engine(db2)
     self.assertIs(sqlahelper.get_session().bind, db2)
     self.assertIs(sqlahelper.get_session().bind, sqlahelper.sessions.default.registry.registry.value.bind)
Пример #14
0
def main(global_config, **settings):
    engine = engine_from_config(settings)
    sqlahelper.add_engine(engine)
    config = Configurator(settings=settings,
        root_factory='.models.ShirlyResource')
    config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')
    config.include('.')
    config.scan()
    return config.make_wsgi_app()
Пример #15
0
def init_engine(config):
    engine = create_engine(
        config['uri'],
        echo=config['echo'],
        pool_recycle=config['pool_recycle'],
        convert_unicode=True
    )

    add_engine(engine)
Пример #16
0
def init_engine(config):
    engine = create_engine(
        config.get('SQLALCHEMY_DATABASE_URI'),
            echo=config.get('SQLALCHEMY_ECHO'),
            pool_recycle=config.get('SQLALCHEMY_POOL_RECYCLE'),
            convert_unicode=True
        )

    add_engine(engine)
Пример #17
0
    def loginchange(self):
        new_password = self.request.params.get('newPassword', None)
        new_password_confirm = self.request.params.get('confirmNewPassword',
                                                       None)
        if new_password is None or new_password_confirm is None:
            raise HTTPBadRequest(
                '"newPassword" and "confirmNewPassword" should be \
                   available in request params')

        # check if loggedin
        if not self.request.user:
            raise HTTPUnauthorized('bad credentials')
        if new_password != new_password_confirm:
            raise HTTPBadRequest("the new password and the new password \
                   confirmation don't match")

        u = self.request.user
        u._set_password(new_password)
        u.is_password_changed = True
        DBSession.flush()
        log.info("password changed for user: %s" % self.request.user.username)

        # handle replication
        if 'auth_replication_enabled' in self.request.registry.settings and \
                self.request.registry.settings['auth_replication_enabled'] == \
                'true':  # pragma: no cover
            try:
                log.debug(
                    "trying to find if engine set for replication exists")
                engine = sqlahelper.get_engine('replication')
            except RuntimeError:
                log.debug("engine for replication doesn't exist yet, trying \
                          to create")
                engine = engine_from_config(self.request.registry.settings,
                                            'sqlalchemy_replication.')
                sqlahelper.add_engine(engine, 'replication')

            DBSession2 = scoped_session(sessionmaker(bind=engine))

            dbuser_r = DBSession2.query(User).filter(
                User.id == self.request.user.id)
            result = dbuser_r.all()
            if len(result) == 0:
                msg = 'user not found in replication target database: %s' \
                    % self.request.user.username
                log.exception(msg)
                return HTTPBadRequest(msg)  # pragma nocover
            else:
                u_r = dbuser_r.all()[0]
                u_r._set_password(new_password)
                u_r.is_password_changed = True
                DBSession2.commit()
                log.info("password changed in replication target database \
                    for user: %s" % self.request.user.username)

        return Response('true', cache_control="no-cache")
Пример #18
0
    def setUp(self):
        try:
            engine = sqlahelper.get_engine()
        except:
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': 'sqlite://'})
            sqlahelper.add_engine(engine)

        self._setup_pyramid()
        self._setup_ptah()
Пример #19
0
def setup_source_engines():
    for source_name, source_data in config['SOURCES'].items():
        if source_data['TYPE'] == 'DB':
            db_connection = config['DATABASES'][source_data['CONNECTION']]
            current_db_url = db_url.format(
                NAME=source_data['DATABASE'],
                **db_connection
            )
            engine = sqlalchemy.create_engine(current_db_url)
            sqlahelper.add_engine(engine, source_name)
Пример #20
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    
    engine = engine_from_config(
        settings,
        'sqlalchemy.',
        convert_unicode=False,
        encoding='utf-8'
        )
    sqlahelper.add_engine(engine)

    settings.setdefault('mako.directories','crdppf:templates')
    settings.setdefault('reload_templates',True)
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet',2400)
    config = Configurator(settings=settings, session_factory = my_session_factory)
    config.include(papyrus.includeme)
    config.add_renderer('.js', mako_renderer_factory)
    config.add_renderer('geojson', GeoJSON())

    config.set_request_property(read_tile_date, name='tile_date', reify=True)

    config.add_static_view('static', 'crdppf:static', cache_max_age=3600)

    # ROUTES
    config.add_route('home', '/')
    config.add_route('images', '/static/images/')
    config.add_route('create_extract', 'create_extract')
    config.add_route('get_features', 'get_features')
    config.add_route('set_language', 'set_language')
    config.add_route('get_language', 'get_language')
    config.add_route('get_translation_dictionary', 'get_translation_dictionary')
    config.add_route('get_interface_config', 'get_interface_config')
    config.add_route('get_baselayers_config', 'get_baselayers_config')
    config.add_route('test', 'test')
    config.add_route('formulaire_reglements', 'formulaire_reglements')
    config.add_route('getCadastreList', 'getCadastreList')
    config.add_route('getTopicsList', 'getTopicsList')
    config.add_route('createNewDocEntry', 'createNewDocEntry')
    config.add_route('getLegalDocuments', 'getLegalDocuments')
    config.add_route('map', 'map')

    config.add_route('globalsjs', '/globals.js')

    config.add_route('ogcproxy', '/ogcproxy')

    # VIEWS
    config.add_view('crdppf.views.entry.Entry', route_name = 'home')
    config.add_view('crdppf.views.entry.Entry', route_name = 'images')
    config.add_view('crdppf.views.entry.Entry', route_name='formulaire_reglements')
    config.add_view('crdppf.views.entry.Entry', route_name='test')

    config.scan()

    return config.make_wsgi_app()
Пример #21
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings)
    sqlahelper.add_engine(engine)
    config = Configurator(settings=settings)
    config.include('.fainit')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app()
Пример #22
0
 def test_multiple_engines(self):
     default = sa.create_engine(self.db1.url)
     stats = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(default)
     sqlahelper.add_engine(stats, "stats")
     # Can we retrieve the engines?
     self.assertIs(sqlahelper.get_engine(), default)
     self.assertIs(sqlahelper.get_engine("default"), default)
     self.assertIs(sqlahelper.get_engine("stats"), stats)
     # Are the session binding and base binding set correctly?
     self.assertIs(sqlahelper.get_session().bind, default)
     self.assertIs(sqlahelper.get_base().metadata.bind, default)
Пример #23
0
 def test_multiple_engines(self):
     default = sa.create_engine(self.db1.url)
     stats = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(default)
     sqlahelper.add_engine(stats, "stats")
     # Can we retrieve the engines?
     self.assertIs(sqlahelper.get_engine(), default)
     self.assertIs(sqlahelper.get_engine("default"), default)
     self.assertIs(sqlahelper.get_engine("stats"), stats)
     # Are the session binding and base binding set correctly?
     self.assertIs(sqlahelper.get_session().bind, default)
     self.assertIs(sqlahelper.get_base().metadata.bind, default)
Пример #24
0
 def test_multiple_engines_without_default(self):
     db1 = sa.create_engine(self.db1.url)
     db2 = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(db1, "db1")
     sqlahelper.add_engine(db2, "db2")
     # Can we retrieve the engines?
     self.assertIs(sqlahelper.get_engine("db1"), db1)
     self.assertIs(sqlahelper.get_engine("db2"), db2)
     # There should be no default engine
     self.assertIsNone(sqlahelper.get_session().bind)
     self.assertIsNone(sqlahelper.get_base().metadata.bind)
     self.assertIsNone(sqlahelper.get_engine())
Пример #25
0
    def loginchange(self):
        new_password = self.request.params.get('newPassword', None)
        new_password_confirm = self.request.params.get('confirmNewPassword', None)
        if new_password is None or new_password_confirm is None:
            raise HTTPBadRequest('"newPassword" and "confirmNewPassword" should be \
                   available in request params')

        # check if loggedin
        if not self.request.user:
            raise HTTPUnauthorized('bad credentials')
        if new_password != new_password_confirm:
            raise HTTPBadRequest("the new password and the new password \
                   confirmation don't match")

        u = self.request.user
        u._set_password(new_password)
        u.is_password_changed = True
        DBSession.flush()
        log.info("password changed for user: %s" % self.request.user.username)

        # handle replication
        if 'auth_replication_enabled' in self.request.registry.settings and \
                self.request.registry.settings['auth_replication_enabled'] == \
                'true':  # pragma: no cover
            try:
                log.debug("trying to find if engine set for replication exists")
                engine = sqlahelper.get_engine('replication')
            except RuntimeError:
                log.debug("engine for replication doesn't exist yet, trying \
                          to create")
                engine = engine_from_config(
                    self.request.registry.settings,
                    'sqlalchemy_replication.')
                sqlahelper.add_engine(engine, 'replication')

            DBSession2 = scoped_session(sessionmaker(bind=engine))

            dbuser_r = DBSession2.query(User).filter(User.id == self.request.user.id)
            result = dbuser_r.all()
            if len(result) == 0:
                msg = 'user not found in replication target database: %s' \
                    % self.request.user.username
                log.exception(msg)
                return HTTPBadRequest(msg)  # pragma nocover
            else:
                u_r = dbuser_r.all()[0]
                u_r._set_password(new_password)
                u_r.is_password_changed = True
                DBSession2.commit()
                log.info("password changed in replication target database \
                    for user: %s" % self.request.user.username)

        return Response('true', cache_control="no-cache")
Пример #26
0
 def test_multiple_engines_without_default(self):
     db1 = sa.create_engine(self.db1.url)
     db2 = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(db1, "db1")
     sqlahelper.add_engine(db2, "db2")
     # Can we retrieve the engines?
     self.assertIs(sqlahelper.get_engine("db1"), db1)
     self.assertIs(sqlahelper.get_engine("db2"), db2)
     # There should be no default engine
     self.assertIsNone(sqlahelper.get_session().bind)
     self.assertIsNone(sqlahelper.get_base().metadata.bind)
     self.assertIsNone(sqlahelper.get_engine())
Пример #27
0
def includeme(config):
    settings = config.registry.settings

    # add default values for some global settings
    templates_dir = list(filter(
        None, settings.get('templates_dir', '').splitlines()))
    templates_dir.append('pygall:templates')
    settings['mako.directories'] = templates_dir
    if 'photos_dir' not in settings:
        settings['photos_dir'] = 'photos'
    if 'upload_dir' not in settings:
        settings['upload_dir'] = 'upload'
    allow_cdn = asbool(settings.get('allow_cdn', 'false'))
    settings['allow_cdn'] = allow_cdn
    ip.set_dest_dir(settings['photos_dir'])
    mkdir_p(settings['upload_dir'])

    init_security(settings)
    init_resources(settings)

    authentication_policy = AuthTktAuthenticationPolicy(
            settings['authtkt_secret'], callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()

    config.add_settings(settings)
    config.set_root_factory(RootFactory)
    config.set_locale_negotiator(default_locale_negotiator)
    config.set_authentication_policy(authentication_policy)
    config.set_authorization_policy(authorization_policy)

    # initialize database
    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)
    config.include(pyramid_tm.includeme)

    # formalchemy
    config.include('pyramid_formalchemy')
    config.include('fa.jquery')
    config.formalchemy_admin('admin', package='pygall',
            view='fa.jquery.pyramid.ModelView', factory=FAModelsFactory)

    # i18n
    config.add_translation_dirs('pygall:locale')

    # bind the mako renderer to other file extensions
    config.add_renderer('.mako', mako_renderer_factory)
    config.add_renderer('jsonp', JSONP(param_name='callback'))

    config.include(add_routes)
    config.include(add_views)

    config.scan('pygall')
Пример #28
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    add_engine(engine)
    session = get_session()
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = MyModel(name='one', value=1)
        session.add(model)
Пример #29
0
    def setUp(self):
        if self._init_sqla:
            try:
                engine = sqlahelper.get_engine()
            except:  # pragma: no cover
                engine = sqlalchemy.engine_from_config(
                    {'sqlalchemy.url': 'sqlite://'})
                sqlahelper.add_engine(engine)

        self.init_pyramid()

        if self._init_ptah:  # pragma: no cover
            self.init_ptah()
Пример #30
0
Файл: app.py Проект: mcdonc/ptah
def sqla_initializing(ev):
    url = SQLA.url
    if url:
        engine_args = {}
        if SQLA.cache:
            engine_args['execution_options'] = \
                {'compiled_cache': SQL_compiled_cache}
        try:
            engine = sqlahelper.get_engine()
        except:
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': url}, 'sqlalchemy.', **engine_args)
            sqlahelper.add_engine(engine)
Пример #31
0
    def setUp(self):
        if self._init_sqla:
            try:
                engine = sqlahelper.get_engine()
            except: # pragma: no cover
                engine = sqlalchemy.engine_from_config(
                    {'sqlalchemy.url': 'sqlite://'})
                sqlahelper.add_engine(engine)

        self.init_pyramid()

        if self._init_ptah: # pragma: no cover
            self.init_ptah()
Пример #32
0
def initializing(ev):
    # auth
    if not SECURITY.secret:
        SECURITY.secret = uuid.uuid4().get_hex()

    pname = SECURITY.policy
    if pname not in ('', 'no-policy'):
        policyFactory, attrs, kw = types[pname]

        settings = []
        for attr in attrs:
            settings.append(SECURITY.get(attr))

        kwargs = {'wild_domain': False}
        for attr in kw:
            kwargs[attr] = SECURITY.get(attr)

        policy = policyFactory(*settings, **kwargs)
        config.registry.registerUtility(policy, IAuthenticationPolicy)

    if SECURITY.authorization:
        config.registry.registerUtility(
            ACLAuthorizationPolicy(), IAuthorizationPolicy)

    # mail
    smtp_mailer = SMTPMailer(
        hostname = MAIL.host,
        port = MAIL.port,
        username = MAIL.username or None,
        password = MAIL.password or None,
        no_tls = MAIL.no_tls,
        force_tls = MAIL.force_tls,
        debug_smtp = MAIL.debug)

    MAIL.Mailer = DirectMailDelivery(smtp_mailer)
    MAIL.full_from_address = formataddr((MAIL.from_name, MAIL.from_address))

    # sqla
    url = SQLA.url
    if url:
        engine_args = {}
        if SQLA.cache:
            engine_args['execution_options'] = \
                {'compiled_cache': SQL_compiled_cache}
        try:
            engine = sqlahelper.get_engine()
        except:
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': url}, 'sqlalchemy.', **engine_args)
            sqlahelper.add_engine(engine)
Пример #33
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     from sqlahelper import add_engine, get_session
     engine = create_engine('sqlite://')
     add_engine(engine)
     from .models import (
         Base,
         MyModel,
         )
     self.session = get_session()
     Base.metadata.create_all(engine)
     self.session = get_session()
     self.model = MyModel(name='one', value=55)
     self.session.add(self.model)
Пример #34
0
def load_database(database=settings.DATABASE):
    engine = sqlalchemy.engine_from_config(database, prefix='')
    sqlahelper.add_engine(engine)
    tlogger.info("database set up: %s" % engine)
    for package in settings.INSTALLED_APPS:
        try:
            importlib.import_module(package + ".models")
        except ImportError:
            result = "failed"
        else:
            result = "done"
        finally:
            tlogger.debug("loading models: %s.models.. %s" % (package, result))
    Base = sqlahelper.get_base()
    tlogger.info('creating database tables')
    Base.metadata.create_all(engine)        
Пример #35
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    add_engine(engine)
    authentication_policy = WhoV2AuthenticationPolicy(settings['who.url'], 'auth_tkt')
    authorization_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings)
    config.set_authentication_policy(authentication_policy)
    config.set_authorization_policy(authorization_policy)
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/', factory=find_object)
    config.add_route('remember', '/remember')
    config.add_route('forget', '/forget')
    config.scan()
    return config.make_wsgi_app()
Пример #36
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings)
    sqlahelper.add_engine(engine)
    settings = get_makopath()
    config = Configurator(root_factory=Root,
                          settings=settings,
                          session_factory=my_session_factory)
    config.include('pyramid_tm')
    config.add_route('home', '/')
    config.add_route('deposit', '/deposit')
    config.add_route('withdraw', '/withdraw')
    config.add_static_view('static', 'bankaccount:static')
    config.scan('.views')
    return config.make_wsgi_app()
Пример #37
0
def set_up_common():
    c2cgeoportal.schema = "main"
    c2cgeoportal.srid = 21781
    functionality.FUNCTIONALITIES_TYPES = None

    # if test.in does not exist (because the z3c.recipe.filetemplate
    # part hasn"t been executed) then db_url is None
    if db_url is None:  # pragma: no cover
        return

    # verify that we have a working database connection before going
    # forward
    from sqlalchemy import create_engine
    from sqlalchemy.exc import OperationalError
    engine = create_engine(db_url)
    try:
        engine.connect()
    except OperationalError:  # pragma: no cover
        return

    import sqlahelper
    sqlahelper.add_engine(engine)

    import alembic.config
    import sys
    sys.argv = [
        "alembic", "-c", "c2cgeoportal/tests/functional/alembic.ini",
        "upgrade", "head"
    ]
    try:
        alembic.config.main()
    except SystemExit:  # alembic call the exit method!
        pass
    sys.argv = [
        "alembic", "-c", "c2cgeoportal/tests/functional/alembic_static.ini",
        "upgrade", "head"
    ]
    try:
        alembic.config.main()
    except SystemExit:  # alembic call the exit method!
        pass
Пример #38
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    engine = engine_from_config(
        settings,
        'sqlalchemy.')
    sqlahelper.add_engine(engine)

    dbreflection.init(engine)

    settings.setdefault('mako.directories','las_extractor:templates')
    settings.setdefault('reload_templates',True)

    settings.update(yaml.load(file(settings.get('app.cfg'))))

    config = Configurator(settings=settings)

    config.include('pyramid_mako')

    config.add_subscriber('las_extractor.i18n.add_renderer_globals',
                      'pyramid.events.BeforeRender')
    config.add_subscriber('las_extractor.i18n.add_localizer',
                      'pyramid.events.NewRequest')

    config.add_translation_dirs('las_extractor:locale/')

    config.add_renderer('jsonp', JSONP(param_name='callback'))

    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')

    config.add_route('lidar_profile', '/lidar/profile')
    config.add_route('lidar_csv', '/lidar/lidarprofil.csv')
    config.add_route('lidar_kml', '/lidar/kml')
    config.add_route('lidar_shp', '/lidar/shp.zip')
    config.add_route('lidar','/lidar')

    config.scan()
    return config.make_wsgi_app()
Пример #39
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    engine = engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)

    dbreflection.init(engine)

    settings.setdefault('mako.directories', 'las_extractor:templates')
    settings.setdefault('reload_templates', True)

    settings.update(yaml.load(file(settings.get('app.cfg'))))

    config = Configurator(settings=settings)

    config.include('pyramid_mako')

    config.add_subscriber('las_extractor.i18n.add_renderer_globals',
                          'pyramid.events.BeforeRender')
    config.add_subscriber('las_extractor.i18n.add_localizer',
                          'pyramid.events.NewRequest')

    config.add_translation_dirs('las_extractor:locale/')

    config.add_renderer('jsonp', JSONP(param_name='callback'))

    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')

    config.add_route('lidar_profile', '/lidar/profile')
    config.add_route('lidar_csv', '/lidar/lidarprofil.csv')
    config.add_route('lidar_kml', '/lidar/kml')
    config.add_route('lidar_shp', '/lidar/shp.zip')
    config.add_route('lidar', '/lidar')

    config.scan()
    return config.make_wsgi_app()
Пример #40
0
def set_up_common():
    c2cgeoportal.schema = "main"
    c2cgeoportal.srid = 21781
    functionality.FUNCTIONALITIES_TYPES = None

    # if test.in does not exist (because the z3c.recipe.filetemplate
    # part hasn"t been executed) then db_url is None
    if db_url is None:  # pragma: no cover
        return

    # verify that we have a working database connection before going
    # forward
    from sqlalchemy import create_engine
    from sqlalchemy.exc import OperationalError
    engine = create_engine(db_url)
    try:
        engine.connect()
    except OperationalError:  # pragma: no cover
        return

    import sqlahelper
    sqlahelper.add_engine(engine)

    import alembic.config
    import sys
    sys.argv = [
        "alembic", "-c", "c2cgeoportal/tests/functional/alembic.ini", "upgrade", "head"
    ]
    try:
        alembic.config.main()
    except SystemExit:  # alembic call the exit method!
        pass
    sys.argv = [
        "alembic", "-c", "c2cgeoportal/tests/functional/alembic_static.ini", "upgrade", "head"
    ]
    try:
        alembic.config.main()
    except SystemExit:  # alembic call the exit method!
        pass
Пример #41
0
def main():
    if len(sys.argv) != 2:
        sys.exit("Usage: python -m drkpr.scripts.create_db INI_FILE")
    ini_file = sys.argv[1]
    logging.config.fileConfig(ini_file)
    log = logging.getLogger(__name__)
    app = get_app(ini_file, "myapp")
    settings = app.registry.settings

    engine = sqlalchemy.engine_from_config(settings,
                                           prefix="sqlalchemy.",
                                           pool_recycle=3600,
                                           convert_unicode=True)
    sqlahelper.add_engine(engine)
    Base = sqlahelper.get_base()
    Session = sqlahelper.get_session()

    log.info("Create testing user accounts ...")
    random.seed("whatever")
    for i in range(0, 100):
        sur_name = sur_names[random.randint(0, len(sur_names) - 1)]
        given_name = given_names[random.randint(0, len(given_names) - 1)]
        username = "******" % (sur_name, given_name)
        try:
            q = Session.query(model.DKUser)
            r = q.get(username)
            if not r:
                user = model.DKUser()
                user.username = username
                user.roles = ":".join(["", model.ROLE_USER, ""])
                user.passwd = hashlib.md5("cpksecurity").hexdigest()
                user.master_email = "*****@*****.**" % username
                user.actived = True
                Session.add(user)
                log.info(" Account '%s' setup complete." % username)
            else:
                log.info("Account '%s' already setup." % username)
        except Exception, e:
            print e
Пример #42
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    engine = engine_from_config(
        settings,
        'sqlalchemy.')
    sqlahelper.add_engine(engine)

    dbreflection.init(engine)

    settings.setdefault('mako.directories','historic_cadastre:templates')
    settings.setdefault('reload_templates',True)

    config = Configurator(settings=settings)
    
    config.include('pyramid_mako')

    config.add_mako_renderer('.html')
    config.add_mako_renderer('.js')
    
    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')
    config.add_route('viewer', '/viewer.js')
    config.add_route('image_proxy','/img/{type}/{id}')
    config.add_route('pdf_proxy','/pdf/{type}/{id}')

    # print proxy routes
    config.add_route('printproxy', '/printproxy')
    config.add_route('printproxy_info', '/printproxy/info.json')
    config.add_route('printproxy_create', '/printproxy/create.json')
    config.add_route('printproxy_get', '/printproxy/{file}.printout')

    # mutation
    config.add_route('mutation_list', '/mutation/list')

    config.scan()
    return config.make_wsgi_app()
Пример #43
0
def main(global_config, **settings):
    """
    This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.include('pyramid_tm')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('view_wiki', '/')
    config.add_route('view_page', '/{pagename}')
    config.add_route('add_page', '/add_page/{pagename}')
    config.add_route('edit_page', '/{pagename}/edit_page')
    config.scan()

    # sqlalchemyを有効に
    engine = engine_from_config(settings)
    sqlahelper.add_engine(engine)

    return config.make_wsgi_app()
Пример #44
0
def main():
    if len(sys.argv) != 2:
        sys.exit("Usage: python -m drkpr.scripts.create_db INI_FILE")
    ini_file = sys.argv[1]
    logging.config.fileConfig(ini_file)
    log = logging.getLogger(__name__)
    app = get_app(ini_file, "myapp")
    settings = app.registry.settings

    engine = sqlalchemy.engine_from_config(settings, prefix="sqlalchemy.",
                pool_recycle=3600, convert_unicode=True)
    sqlahelper.add_engine(engine)
    Base = sqlahelper.get_base()
    Session = sqlahelper.get_session()

    log.info("Create testing user accounts ...")
    random.seed("whatever")
    for i in range(0,100):
        sur_name = sur_names[random.randint(0, len(sur_names)-1)]
        given_name = given_names[random.randint(0, len(given_names)-1)]
        username = "******" % (sur_name, given_name)
        try:
            q = Session.query(model.DKUser)
            r = q.get(username)
            if not r:
                user = model.DKUser()
                user.username = username
                user.roles = ":".join(["", model.ROLE_USER, ""])
                user.passwd = hashlib.md5("cpksecurity").hexdigest()
                user.master_email = "*****@*****.**" % username
                user.actived = True
                Session.add(user)
                log.info(" Account '%s' setup complete." % username)
            else:
                log.info("Account '%s' already setup." % username)
        except Exception, e:
            print e
Пример #45
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    # Here you can insert any code to modify the ``settings`` dict.
    # You can:
    # * Add additional keys to serve as constants or "global variables" in the
    #   application.
    # * Set default values for settings that may have been omitted.
    # * Override settings that you don't want the user to change.
    # * Raise an exception if a setting is missing or invalid.
    # * Convert values from strings to their intended type.

    # Create the Pyramid Configurator.
    config = Configurator(settings=settings)
    config.include("pyramid_handlers")
    config.include("akhet")

    # Initialize database
    engine = sqlalchemy.engine_from_config(settings, prefix="sqlalchemy.")
    sqlahelper.add_engine(engine)
    config.include("pyramid_tm")

    # Configure Beaker sessions and caching
    session_factory = pyramid_beaker.session_factory_from_settings(settings)
    config.set_session_factory(session_factory)
    pyramid_beaker.set_cache_regions_from_settings(settings)

    # Configure Babel
    config.add_translation_dirs("drkpr:locale")

    # Configure renderers and event subscribers
    config.add_renderer(".html", "pyramid.mako_templating.renderer_factory")
    config.add_subscriber("drkpr.subscribers.create_url_generator",
                          "pyramid.events.ContextFound")
    config.add_subscriber("drkpr.subscribers.add_renderer_globals",
                          "pyramid.events.BeforeRender")
    config.add_subscriber('drkpr.subscribers.add_localizer',
                          'pyramid.events.NewRequest')

    # Set up view handlers
    config.include("drkpr.handlers")

    # Set up other routes and views
    # ** If you have non-handler views, create create a ``drkpr.views``
    # ** module for them and uncomment the next line.
    #
    #config.scan("drkpr.views")

    # Mount a static view overlay onto "/". This will serve, e.g.:
    # ** "/robots.txt" from "drkpr/static/robots.txt" and
    # ** "/images/logo.png" from "drkpr/static/images/logo.png".
    #
    config.add_static_route("drkpr", "static", cache_max_age=3600)

    # Mount a static subdirectory onto a URL path segment.
    # ** This not necessary when using add_static_route above, but it's the
    # ** standard Pyramid way to serve static files under a URL prefix (but
    # ** not top-level URLs such as "/robots.txt"). It can also serve files from
    # ** third-party packages, or point to an external HTTP server (a static
    # ** media server).
    # ** The first commented example serves URLs under "/static" from the
    # ** "drkpr/static" directory. The second serves URLs under
    # ** "/deform" from the third-party ``deform`` distribution.
    #
    config.add_static_view("static", "drkpr:static")
    #config.add_static_view("deform", "deform:static")

    return config.make_wsgi_app()
Пример #46
0
def main():
    if len(sys.argv) != 2:
        sys.exit("Usage: python -m drkpr.scripts.create_db INI_FILE")
    ini_file = sys.argv[1]
    logging.config.fileConfig(ini_file)
    log = logging.getLogger(__name__)
    app = get_app(ini_file, "myapp")
    settings = app.registry.settings

    engine = sqlalchemy.engine_from_config(settings,
                                           prefix="sqlalchemy.",
                                           pool_recycle=3600,
                                           convert_unicode=True)
    sqlahelper.add_engine(engine)
    Base = sqlahelper.get_base()
    Session = sqlahelper.get_session()

    # Create the tables if they don't already exist
    log.info("Initialize database ...")
    Base.metadata.create_all(bind=Session.bind, checkfirst=True)

    #create default privileges
    log.info("Populate default privileges ...")
    log.info("nothing here...")
    log.info("Populate default privileges done.")

    #create default roles
    log.info("Populate default roles ...")
    q = Session.query(model.DKRole)
    if not q.all():
        records = [
            model.DKRole(model.ROLE_SYSADMIN),
            model.DKRole(model.ROLE_USER),
        ]
        Session.add_all(records)
        log.info("Populate default roles done.")
    else:
        log.info("Roles already exist.")

    log.info("Populate default roles done.")

    #create default system parameters
    log.info("Populate default system parameters ...")
    q = Session.query(model.DKSystem)
    if not q.all():
        records = [
            model.DKSystem("master_key_status", model.SS_SERVICE_NO_KEY),
            model.DKSystem("service_key_gen_status",
                           model.SS_SERVICE_NOT_AVAIL),
            model.DKSystem("service_key_revoke_status",
                           model.SS_SERVICE_NOT_AVAIL),
        ]
        Session.add_all(records)
        log.info("Populate default system parameters done.")
    else:
        log.info("System parameters exists.")

    #create default admin account
    log.info("Create default admin account ...")
    q = Session.query(model.DKUser)
    r = q.get("sysadmin")
    if not r:
        user = model.DKUser()
        user.username = "******"
        user.roles = ":".join(["", model.ROLE_SYSADMIN, ""])
        user.passwd = hashlib.md5("sysadmin").hexdigest()
        user.master_email = "*****@*****.**"
        user.actived = True
        Session.add(user)
        log.info("Admin account setup complete.")
    else:
        log.info("Admin account already setup.")

    transaction.commit()
Пример #47
0
def includeme(config):
    """ This function returns a Pyramid WSGI application.
    """

    # update the settings object from the YAML application config file
    settings = config.get_settings()
    settings.update(c2c.template.get_config(settings.get("app.cfg")))

    call_hook(settings, "after_settings", settings)

    config.add_request_method(_create_get_user_from_request(settings),
                              name="user",
                              property=True)

    # configure 'locale' dir as the translation dir for c2cgeoportal app
    config.add_translation_dirs("c2cgeoportal:locale/")

    # initialize database
    engine = sqlalchemy.engine_from_config(settings, "sqlalchemy.")
    sqlahelper.add_engine(engine)
    config.include(pyramid_tm.includeme)
    config.include("pyramid_closure")

    if "sqlalchemy_slave.url" in settings and \
            settings["sqlalchemy.url"] != settings["sqlalchemy_slave.url"]:  # pragma: nocover
        # Setup a slave DB connection and add a tween to switch between it and the default one.
        log.info("Using a slave DB for reading")
        engine_slave = sqlalchemy.engine_from_config(config.get_settings(),
                                                     "sqlalchemy_slave.")
        sqlahelper.add_engine(engine_slave, name="slave")
        config.add_tween("c2cgeoportal.models.db_chooser_tween_factory",
                         over="pyramid_tm.tm_tween_factory")

    # initialize the dbreflection module
    dbreflection.init(engine)

    # dogpile.cache configuration
    caching.init_region(settings["cache"])
    caching.invalidate_region()

    # Register a tween to get back the cache buster path.
    config.add_tween("c2cgeoportal.lib.cacheversion.CachebusterTween")

    # bind the mako renderer to other file extensions
    add_mako_renderer(config, ".html")
    add_mako_renderer(config, ".js")
    config.include("pyramid_chameleon")

    # add the "geojson" renderer
    config.add_renderer("geojson", GeoJSON())

    # add decimal json renderer
    config.add_renderer("decimaljson", DecimalJSON())

    # add the "xsd" renderer
    config.add_renderer(
        "xsd", XSD(sequence_callback=dbreflection._xsd_sequence_callback))

    # add the set_user_validator directive, and set a default user
    # validator
    config.add_directive("set_user_validator", set_user_validator)
    config.set_user_validator(default_user_validator)

    if settings.get("ogcproxy_enable", False):  # pragma: no cover
        # add an OGCProxy view
        config.add_route_predicate("ogc_server", OgcproxyRoutePredicate)
        config.add_route("ogcproxy", "/ogcproxy", ogc_server=True)
        config.add_view("papyrus_ogcproxy.views:ogcproxy",
                        route_name="ogcproxy")

    # add routes to the mapserver proxy
    config.add_route_predicate("mapserverproxy", MapserverproxyRoutePredicate)
    config.add_route(
        "mapserverproxy",
        "/mapserv_proxy",
        mapserverproxy=True,
        pregenerator=C2CPregenerator(role=True),
    )

    # add route to the tinyows proxy
    config.add_route(
        "tinyowsproxy",
        "/tinyows_proxy",
        pregenerator=C2CPregenerator(role=True),
    )

    # add routes to csv view
    config.add_route("csvecho", "/csv", request_method="POST")

    # add route to the export GPX/KML view
    config.add_route("exportgpxkml", "/exportgpxkml")

    # add routes to the echo service
    config.add_route("echo", "/echo", request_method="POST")

    # add routes to the entry view class
    config.add_route("base", "/", static=True)
    config.add_route("loginform", "/login.html", request_method="GET")
    add_cors_route(config, "/login", "login")
    config.add_route("login", "/login", request_method="POST")
    add_cors_route(config, "/logout", "login")
    config.add_route("logout", "/logout", request_method="GET")
    add_cors_route(config, "/loginchange", "login")
    config.add_route("loginchange", "/loginchange", request_method="POST")
    add_cors_route(config, "/loginresetpassword", "login")
    config.add_route("loginresetpassword",
                     "/loginresetpassword",
                     request_method="POST")
    add_cors_route(config, "/loginuser", "login")
    config.add_route("loginuser", "/loginuser", request_method="GET")
    config.add_route("testi18n", "/testi18n.html", request_method="GET")
    config.add_route("apijs", "/api.js", request_method="GET")
    config.add_route("xapijs", "/xapi.js", request_method="GET")
    config.add_route("apihelp", "/apihelp.html", request_method="GET")
    config.add_route("xapihelp", "/xapihelp.html", request_method="GET")
    config.add_route(
        "themes",
        "/themes",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("invalidate", "/invalidate", request_method="GET")

    # checker routes, Checkers are web services to test and assess that
    # the application is correctly functioning.
    # These web services are used by tools like (nagios).
    config.add_route("checker_routes", "/checker_routes", request_method="GET")
    config.add_route("checker_lang_files",
                     "/checker_lang_files",
                     request_method="GET")
    config.add_route("checker_pdf3", "/checker_pdf3", request_method="GET")
    config.add_route("checker_fts", "/checker_fts", request_method="GET")
    config.add_route("checker_theme_errors",
                     "/checker_theme_errors",
                     request_method="GET")
    config.add_route("checker_phantomjs",
                     "/checker_phantomjs",
                     request_method="GET")
    # collector
    config.add_route("check_collector",
                     "/check_collector",
                     request_method="GET")

    # print proxy routes
    config.add_route("printproxy", "/printproxy", request_method="HEAD")
    add_cors_route(config, "/printproxy/*all", "print")
    config.add_route(
        "printproxy_capabilities",
        "/printproxy/capabilities.json",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("printproxy_report_create",
                     "/printproxy/report.{format}",
                     request_method="POST",
                     header=JSON_CONTENT_TYPE)
    config.add_route("printproxy_status",
                     "/printproxy/status/{ref}.json",
                     request_method="GET")
    config.add_route("printproxy_cancel",
                     "/printproxy/cancel/{ref}",
                     request_method="DELETE")
    config.add_route("printproxy_report_get",
                     "/printproxy/report/{ref}",
                     request_method="GET")

    # full text search routes
    add_cors_route(config, "/fulltextsearch", "fulltextsearch")
    config.add_route("fulltextsearch", "/fulltextsearch")

    # Access to raster data
    add_cors_route(config, "/raster", "raster")
    config.add_route("raster", "/raster", request_method="GET")

    add_cors_route(config, "/profile.{ext}", "profile")
    config.add_route("profile.csv", "/profile.csv", request_method="POST")
    config.add_route("profile.json", "/profile.json", request_method="POST")

    # shortener
    add_cors_route(config, "/short/create", "shortner")
    config.add_route("shortener_create",
                     "/short/create",
                     request_method="POST")
    config.add_route("shortener_get", "/short/{ref}", request_method="GET")

    # Geometry processing
    config.add_route("difference", "/difference", request_method="POST")

    # PDF report tool
    config.add_route("pdfreport",
                     "/pdfreport/{layername}/{id}",
                     request_method="GET")

    # add routes for the "layers" web service
    add_cors_route(config, "/layers/*all", "layers")
    config.add_route("layers_count",
                     "/layers/{layer_id:\\d+}/count",
                     request_method="GET")
    config.add_route(
        "layers_metadata",
        "/layers/{layer_id:\\d+}/md.xsd",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("layers_read_many",
                     "/layers/{layer_id:\\d+,?(\\d+,)*\\d*$}",
                     request_method="GET")  # supports URLs like /layers/1,2,3
    config.add_route("layers_read_one",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="GET")
    config.add_route("layers_create",
                     "/layers/{layer_id:\\d+}",
                     request_method="POST",
                     header=JSON_CONTENT_TYPE)
    config.add_route("layers_update",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="PUT",
                     header=JSON_CONTENT_TYPE)
    config.add_route("layers_delete",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="DELETE")
    config.add_route(
        "layers_enumerate_attribute_values",
        "/layers/{layer_name}/values/{field_name}",
        request_method="GET",
        pregenerator=C2CPregenerator(),
    )
    # there's no view corresponding to that route, it is to be used from
    # mako templates to get the root of the "layers" web service
    config.add_route("layers_root", "/layers/", request_method="HEAD")

    # Resource proxy (load external url, useful when loading non https content)
    config.add_route("resourceproxy", "/resourceproxy", request_method="GET")

    # pyramid_formalchemy's configuration
    config.include("pyramid_formalchemy")
    config.include("fa.jquery")

    # define the srid, schema and parentschema
    # as global variables to be usable in the model
    c2cgeoportal.srid = settings["srid"]
    c2cgeoportal.schema = settings["schema"]
    c2cgeoportal.parentschema = settings["parentschema"]
    c2cgeoportal.formalchemy_default_zoom = get_setting(
        settings, ("admin_interface", "map_zoom"),
        c2cgeoportal.formalchemy_default_zoom)
    c2cgeoportal.formalchemy_default_x = get_setting(
        settings, ("admin_interface", "map_x"),
        c2cgeoportal.formalchemy_default_x)
    c2cgeoportal.formalchemy_default_y = get_setting(
        settings, ("admin_interface", "map_y"),
        c2cgeoportal.formalchemy_default_y)
    c2cgeoportal.formalchemy_available_functionalities = get_setting(
        settings, ("admin_interface", "available_functionalities"),
        c2cgeoportal.formalchemy_available_functionalities)
    c2cgeoportal.formalchemy_available_metadata = get_setting(
        settings, ("admin_interface", "available_metadata"),
        c2cgeoportal.formalchemy_available_metadata)
    c2cgeoportal.formalchemy_available_metadata = [
        e if isinstance(e, basestring) else e.get("name")
        for e in c2cgeoportal.formalchemy_available_metadata
    ]

    config.add_route("checker_all", "/checker_all", request_method="GET")

    config.add_route("version_json", "/version.json", request_method="GET")

    stats.init(config)

    # scan view decorator for adding routes
    config.scan(ignore=["c2cgeoportal.tests", "c2cgeoportal.scripts"])

    if "subdomains" in settings:  # pragma: no cover
        config.registry.registerUtility(MultiDomainStaticURLInfo(),
                                        IStaticURLInfo)

    # add the static view (for static resources)
    _add_static_view(config, "static", "c2cgeoportal:static")
    _add_static_view(config, "project", "c2cgeoportal:project")

    add_admin_interface(config)
    add_static_view(config)

    # Handles the other HTTP errors raised by the views. Without that,
    # the client receives a status=200 without content.
    config.add_view(error_handler, context=HTTPException)

    _log_versions(settings)
Пример #48
0
import os
import oedialect  # noqa pylint: disable=unused-import
from configobj import ConfigObj
from sqlalchemy import create_engine
import sqlahelper

from wam import settings  # pylint: disable=import-error

# add local config file
fred_config = ConfigObj(
    os.path.join(settings.BASE_DIR, 'WAM_APP_FRED', 'config', 'fred_app.cfg'))

OEP_ACCESS = fred_config['WAM_APP_FRED']['OEP_ACCESS']

LOCAL_TESTING = fred_config['WAM_APP_FRED'].as_bool('LOCAL_TESTING')
wam_config = settings.config['DATABASES'][OEP_ACCESS]

# ##########################################SQLAlchemy ENGINE#######################################
if not LOCAL_TESTING:
    # db connection string for sqlalchemy-engine
    if OEP_ACCESS == 'OEP':
        DB_URL = '{ENGINE}://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}'.format(
            **wam_config)
    elif OEP_ACCESS == 'OEP_DIALECT':
        DB_URL = '{ENGINE}://{USER}:{TOKEN}@{HOST}'.format(**wam_config)
    engine = create_engine(DB_URL)
    sqlahelper.add_engine(engine, 'oep_engine')
# ##################################################################################################
Пример #49
0
 def setUp(self):
     from pyramid.config import Configurator
     self.engine = sqlahelper.add_engine(url="sqlite://")
     self.session = sqlahelper.get_session()()
     self.config = Configurator(autocommit=True)
     self.config.begin()
Пример #50
0
    pgstats = {}
    for pgstat in session.query(PlayerGameStat).\
            filter(PlayerGameStat.game_id == game.game_id).\
            all():
        pgstats[pgstat.player_id] = pgstat

    for pid in elo_deltas.keys():
        try:
            pgstats[pid].ts_delta = elo_deltas[pid]
            session.add(pgstats[pid])
        except:
            log.debug(
                "Unable to save Elo delta value for player_id {0}".format(pid))


#"""
# setup the database engine
engine = create_engine(
    "postgresql+psycopg2://xonstat:xonstat@localhost:5432/xonstatdb")
sqlahelper.add_engine(engine)
initialize_db(engine)
DBSession = sessionmaker(bind=engine)
session = DBSession()
games = session.query(Game).filter(Game.game_type_cd == 'ctf').order_by(
    Game.start_dt).all()
#games = session.query(Game).filter(Game.match_id == '25c731c1-0909-41bc-aea6-ec1882b34ffc').all()
for game in games:
    log.debug("processing game " + str(game.game_id))
    process_ratings(game, session)
session.commit()
#"""
Пример #51
0
def includeme(config):
    """ This function returns a Pyramid WSGI application.
    """

    # update the settings object from the YAML application config file
    settings = config.get_settings()
    settings.update(yaml.load(file(settings.get("app.cfg"))))

    global srid
    global schema
    global parentschema
    global formalchemy_language
    global formalchemy_default_zoom
    global formalchemy_default_x
    global formalchemy_default_y
    global formalchemy_available_functionalities
    global formalchemy_available_metadata

    config.add_request_method(_create_get_user_from_request(settings),
                              name="user",
                              property=True)

    # configure 'locale' dir as the translation dir for c2cgeoportal app
    config.add_translation_dirs("c2cgeoportal:locale/")

    # initialize database
    engine = sqlalchemy.engine_from_config(settings, "sqlalchemy.")
    sqlahelper.add_engine(engine)
    config.include(pyramid_tm.includeme)
    config.include("pyramid_closure")

    # initialize the dbreflection module
    dbreflection.init(engine)

    # dogpile.cache configuration
    caching.init_region(settings["cache"])
    caching.invalidate_region()

    # bind the mako renderer to other file extensions
    add_mako_renderer(config, ".html")
    add_mako_renderer(config, ".js")
    config.include("pyramid_chameleon")

    # add the "geojson" renderer
    config.add_renderer("geojson", GeoJSON())

    # add decimal json renderer
    config.add_renderer("decimaljson", DecimalJSON())

    # add the "xsd" renderer
    config.add_renderer(
        "xsd", XSD(sequence_callback=dbreflection._xsd_sequence_callback))

    # add the set_user_validator directive, and set a default user
    # validator
    config.add_directive("set_user_validator", set_user_validator)
    config.set_user_validator(default_user_validator)

    if settings.get("ogcproxy_enable", True):
        # add an OGCProxy view
        config.add_route("ogcproxy",
                         "/ogcproxy",
                         custom_predicates=(ogcproxy_route_predicate, ))
        config.add_view("papyrus_ogcproxy.views:ogcproxy",
                        route_name="ogcproxy")

    # add routes to the mapserver proxy
    config.add_route(
        "mapserverproxy",
        "/mapserv_proxy",
        custom_predicates=(mapserverproxy_route_predicate, ),
        pregenerator=C2CPregenerator(role=True),
    )

    # add route to the tinyows proxy
    config.add_route(
        "tinyowsproxy",
        "/tinyows_proxy",
        pregenerator=C2CPregenerator(role=True),
    )

    # add routes to csv view
    config.add_route("csvecho", "/csv", request_method="POST")

    # add route to the export GPX/KML view
    config.add_route("exportgpxkml", "/exportgpxkml")

    # add routes to the echo service
    config.add_route("echo", "/echo", request_method="POST")

    # add routes to the entry view class
    config.add_route("loginform", "/login.html", request_method="GET")
    add_cors_route(config, "/login", "login")
    config.add_route("login", "/login", request_method=("GET", "POST"))
    add_cors_route(config, "/logout", "login")
    config.add_route("logout", "/logout", request_method="GET")
    add_cors_route(config, "/loginchange", "login")
    config.add_route("loginchange", "/loginchange", request_method="POST")
    add_cors_route(config, "/loginresetpassword", "login")
    config.add_route("loginresetpassword",
                     "/loginresetpassword",
                     request_method="GET")
    config.add_route("testi18n", "/testi18n.html", request_method="GET")
    config.add_route("apijs", "/api.js", request_method="GET")
    config.add_route("xapijs", "/xapi.js", request_method="GET")
    config.add_route("apihelp", "/apihelp.html", request_method="GET")
    config.add_route("xapihelp", "/xapihelp.html", request_method="GET")
    config.add_route(
        "themes",
        "/themes",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("invalidate", "/invalidate", request_method="GET")

    # checker routes, Checkers are web services to test and assess that
    # the application is correctly functioning.
    # These web services are used by tools like (nagios).
    config.add_route("checker_main", "/checker_main", request_method="GET")
    config.add_route("checker_viewer", "/checker_viewer", request_method="GET")
    config.add_route("checker_edit", "/checker_edit", request_method="GET")
    config.add_route("checker_edit_js",
                     "/checker_edit_js",
                     request_method="GET")
    config.add_route("checker_api", "/checker_api", request_method="GET")
    config.add_route("checker_xapi", "/checker_xapi", request_method="GET")
    config.add_route("checker_lang_files",
                     "/checker_lang_files",
                     request_method="GET")
    config.add_route(
        "checker_printcapabilities",
        "/checker_printcapabilities",
        request_method="GET",
    )
    config.add_route("checker_pdf", "/checker_pdf", request_method="GET")
    config.add_route(
        "checker_print3capabilities",
        "/checker_print3capabilities",
        request_method="GET",
    )
    config.add_route("checker_pdf3", "/checker_pdf3", request_method="GET")
    config.add_route("checker_fts", "/checker_fts", request_method="GET")
    config.add_route("checker_wmscapabilities",
                     "/checker_wmscapabilities",
                     request_method="GET")
    config.add_route("checker_wfscapabilities",
                     "/checker_wfscapabilities",
                     request_method="GET")
    config.add_route("checker_theme_errors",
                     "/checker_theme_errors",
                     request_method="GET")
    # collector
    config.add_route("check_collector",
                     "/check_collector",
                     request_method="GET")

    # print proxy routes
    config.add_route("printproxy", "/printproxy", request_method="HEAD")
    config.add_route(
        "printproxy_info",
        "/printproxy/info.json",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route(
        "printproxy_create",
        "/printproxy/create.json",
        request_method="POST",
    )
    config.add_route(
        "printproxy_get",
        "/printproxy/{file}.printout",
        request_method="GET",
    )
    # V3
    add_cors_route(config, "/printproxy/*all", "print")
    config.add_route(
        "printproxy_capabilities",
        "/printproxy/capabilities.json",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("printproxy_report_create",
                     "/printproxy/report.{format}",
                     request_method="POST",
                     header=JSON_CONTENT_TYPE)
    config.add_route("printproxy_status",
                     "/printproxy/status/{ref}.json",
                     request_method="GET")
    config.add_route("printproxy_cancel",
                     "/printproxy/cancel/{ref}",
                     request_method="DELETE")
    config.add_route("printproxy_report_get",
                     "/printproxy/report/{ref}",
                     request_method="GET")

    # full text search routes
    add_cors_route(config, "/fulltextsearch", "fulltextsearch")
    config.add_route("fulltextsearch", "/fulltextsearch")

    # Access to raster data
    add_cors_route(config, "/raster", "raster")
    config.add_route("raster", "/raster", request_method="GET")

    add_cors_route(config, "/profile.{ext}", "profile")
    config.add_route("profile.csv", "/profile.csv", request_method="POST")
    config.add_route("profile.json", "/profile.json", request_method="POST")

    # shortener
    config.add_route("shortener_create",
                     "/short/create",
                     request_method="POST")
    config.add_route("shortener_get", "/short/{ref}", request_method="GET")

    # Geometry processing
    config.add_route("difference", "/difference", request_method="POST")

    # PDF report tool
    config.add_route("pdfreport",
                     "/pdfreport/{layername}/{id}",
                     request_method="GET")

    # add routes for the "layers" web service
    add_cors_route(config, "/layers/*all", "layers")
    config.add_route("layers_count",
                     "/layers/{layer_id:\\d+}/count",
                     request_method="GET")
    config.add_route(
        "layers_metadata",
        "/layers/{layer_id:\\d+}/md.xsd",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("layers_read_many",
                     "/layers/{layer_id:\\d+,?(\\d+,)*\\d*$}",
                     request_method="GET")  # supports URLs like /layers/1,2,3
    config.add_route("layers_read_one",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="GET")
    config.add_route("layers_create",
                     "/layers/{layer_id:\\d+}",
                     request_method="POST",
                     header=JSON_CONTENT_TYPE)
    config.add_route("layers_update",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="PUT",
                     header=JSON_CONTENT_TYPE)
    config.add_route("layers_delete",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="DELETE")
    config.add_route(
        "layers_enumerate_attribute_values",
        "/layers/{layer_name}/values/{field_name}",
        request_method="GET",
        pregenerator=C2CPregenerator(),
    )
    # there's no view corresponding to that route, it is to be used from
    # mako templates to get the root of the "layers" web service
    config.add_route("layers_root", "/layers/", request_method="HEAD")

    # pyramid_formalchemy's configuration
    config.include("pyramid_formalchemy")
    config.include("fa.jquery")

    # define the srid, schema and parentschema
    # as global variables to be usable in the model
    srid = settings["srid"]
    schema = settings["schema"]
    parentschema = settings["parentschema"]
    formalchemy_default_zoom = get_setting(settings,
                                           ("admin_interface", "map_zoom"),
                                           formalchemy_default_zoom)
    formalchemy_default_x = get_setting(settings, ("admin_interface", "map_x"),
                                        formalchemy_default_x)
    formalchemy_default_y = get_setting(settings, ("admin_interface", "map_y"),
                                        formalchemy_default_y)
    formalchemy_available_functionalities = get_setting(
        settings, ("admin_interface", "available_functionalities"),
        formalchemy_available_functionalities)
    formalchemy_available_metadata = get_setting(
        settings, ("admin_interface", "available_metadata"),
        formalchemy_available_metadata)

    config.add_route("checker_all", "/checker_all", request_method="GET")

    # scan view decorator for adding routes
    config.scan(ignore="c2cgeoportal.tests")

    config.registry.registerUtility(MultiDomainStaticURLInfo(), IStaticURLInfo)

    # add the static view (for static resources)
    _add_static_view(config, "static", "c2cgeoportal:static")
    _add_static_view(config, "project", "c2cgeoportal:project")

    add_admin_interface(config)
    add_static_view(config)

    # Handles the other HTTP errors raised by the views. Without that,
    # the client receives a status=200 without content.
    config.add_view(error_handler, context=HTTPException)
Пример #52
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(
        root_factory=Root,
        settings=settings,
        locale_negotiator=locale_negotiator,
        authentication_policy=create_authentication(settings))

    # overwrite print routes
    config.add_route("lux_printproxy_report_create",
                     "/printproxy/report.{format}",
                     request_method="POST")
    config.add_route("lux_printproxy_report_get",
                     "/printproxy/report/{ref}",
                     request_method="GET")
    config.add_route("lux_printproxy_report_cancel",
                     "/printproxy/cancel/{ref}",
                     request_method="DELETE")
    # mymaps routes
    config.add_route("mymaps", "/mymaps", request_method="HEAD")
    config.add_route("mymaps_image", "/", request_method="HEAD")
    config.add_route("mymaps_getcategories",
                     "mymaps/categories",
                     request_method="GET")
    config.add_route("mymaps_getmaps", "/mymaps/maps", request_method="GET")
    config.add_route("mymaps_features",
                     "/mymaps/features/{map_id}",
                     request_method="GET")
    config.add_route("mymaps_map_info",
                     "/mymaps/map_info/{map_id}",
                     request_method="GET")

    config.add_route("mymaps_create", "/mymaps/create", request_method="POST")
    config.add_route("mymaps_rate", "/mymaps/rate/{map_id}")
    config.add_route("mymaps_update",
                     "/mymaps/update/{map_id}",
                     request_method="PUT")
    config.add_route("mymaps_map",
                     "/mymaps/map/{map_id}",
                     request_method="GET")
    config.add_route("mymaps_comment",
                     "/mymaps/comment/{map_id}",
                     request_method="POST")
    config.add_route("mymaps_upload_image",
                     "/mymaps/upload_image",
                     request_method="POST")
    config.add_route("mymaps_upload_symbol",
                     "/mymaps/upload_symbol",
                     request_method="POST")
    config.add_route("mymaps_get_image",
                     "/mymaps/images/{filename}",
                     request_method="GET")
    config.add_route("mymaps_get_symbol",
                     "/mymaps/symbol/{symbol_id}",
                     request_method="GET")
    config.add_route("mymaps_get_symbols",
                     "/mymaps/symbols",
                     request_method="GET")
    config.add_route("mymaps_delete",
                     "/mymaps/delete/{map_id}",
                     request_method="DELETE")
    config.add_route("mymaps_delete_all_features",
                     "/mymaps/delete_all_features/{map_id}",
                     request_method="DELETE")
    config.add_route("mymaps_delete_feature",
                     "/mymaps/delete_feature/{feature_id}",
                     request_method="DELETE")
    config.add_route("mymaps_save_feature",
                     "/mymaps/save_feature/{map_id}",
                     request_method="POST")
    config.add_route("mymaps_save_features",
                     "/mymaps/save_features/{map_id}",
                     request_method="POST")
    config.add_route("mymaps_copy",
                     "/mymaps/copy/{map_id}",
                     request_method="POST")
    config.add_route("exportgpxkml",
                     "/mymaps/exportgpxkml",
                     request_method="POST")
    # geocoder routes
    config.add_route("reverse_geocode", "/geocode/reverse")
    # pag routes
    config.add_route("pag_url", "/pag")
    # pag routes
    config.add_route("pag_report", "/pag/report/{oid}.pdf")
    config.add_route("pag_files", "/pag/files/{_file}")

    config.include('c2cgeoportal')
    config.include('pyramid_closure')

    config.add_translation_dirs('geoportailv3:locale/')

    # initialize database
    engines = config.get_settings()['sqlalchemy_engines']
    if engines:
        for engine in engines:
            sqlahelper.add_engine(sqlalchemy.create_engine(engines[engine]),
                                  name=engine)

    from geoportailv3.views.authentication import ldap_user_validator, \
        get_user_from_request
    ldap_settings = config.get_settings()['ldap']
    if ldap_settings:
        config.include('pyramid_ldap')
        """Config the ldap connection.
        """

        config.ldap_setup(
            ldap_settings['url'],
            ldap_settings['bind'],
            ldap_settings['passwd'],
        )

        config.ldap_set_login_query(
            ldap_settings['base_dn'],
            filter_tmpl='(login=%(login)s)',
            scope=ldap.SCOPE_SUBTREE,
        )

        config.set_request_property(get_user_from_request,
                                    name='user',
                                    reify=True)

        set_user_validator(config, ldap_user_validator)
    json_renderer = JSON()

    json_renderer.add_adapter(datetime.date, datetime_adapter)
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(Decimal, decimal_adapter)
    config.add_renderer('json', json_renderer)

    mail_config = config.get_settings()['turbomail']
    if mail_config:
        interface.start(mail_config)

    # scan view decorator for adding routes
    config.scan()

    # add the interfaces
    add_interface(config, interface_type=INTERFACE_TYPE_NGEO_CATALOGUE)

    config.add_route("echocsv", "/profile/echocsv", request_method="POST")
    config.add_route('getuserinfo', '/getuserinfo')
    config.add_route('wms', '/ogcproxywms')
    config.add_route('download_sketch', '/downloadsketch')
    config.add_route('download_measurement', '/downloadmeasurement')
    config.add_route('qr', '/qr')
    config.add_route('getfeatureinfo', '/getfeatureinfo')
    config.add_route('getpoitemplate', '/getpoitemplate')
    config.add_route('getremotetemplate', '/getremotetemplate')
    config.add_route('isthemeprivate', '/isthemeprivate')
    return config.make_wsgi_app()
Пример #53
0
def includeme(config):
    """ This function returns a Pyramid WSGI application.
    """

    settings = config.get_settings()

    yaml_config = yaml.load(file(settings.get("app.cfg")))
    settings.update(yaml_config)

    my_session_factory = SignedCookieSessionFactory(
        yaml_config['authtkt_secret'],
        cookie_name=yaml_config['authtkt_cookie_name'],
        timeout=8200
    )
    
    config.set_session_factory(my_session_factory)
    
    engine = engine_from_config(settings, 'sqlalchemy.')

    sqlahelper.add_engine(engine)

    global db_config
    db_config = yaml.load(file(settings.get('database.cfg')))['db_config']
    settings.update(yaml.load(file(settings.get('pdf.cfg'))))

    config.include(papyrus.includeme)
    config.include('pyramid_mako')
    # bind the mako renderer to other file extensions
    add_mako_renderer(config, ".js")

    config.add_renderer('geojson', GeoJSON())

    # add app configuration from db
    read_app_config(settings)

    specific_tmp_path = os.path.join(settings['specific_root_dir'], 'templates')
    specific_static_path = os.path.join(settings['specific_root_dir'], 'static')
    settings.setdefault('mako.directories',['crdppf:templates', specific_tmp_path])
    settings.setdefault('reload_templates',True)
    
    # add the static view (for static resources)
    config.add_static_view('static', 'crdppf:static',cache_max_age=3600)
    config.add_static_view('proj', 'crdppfportal:static', cache_max_age=3600)
     
    # ROUTES
    config.add_route('home', '/')
    config.add_route('images', '/static/images/')
    config.add_route('create_extract', 'create_extract')
    config.add_route('get_features', 'get_features')
    config.add_route('get_property', 'property/get')
    config.add_route('set_language', 'set_language')
    config.add_route('get_language', 'get_language')
    config.add_route('get_translation_dictionary', 'get_translation_dictionary')
    config.add_route('get_translations_list', 'get_translations_list')
    config.add_route('get_interface_config', 'get_interface_config')
    config.add_route('get_baselayers_config', 'get_baselayers_config')
    config.add_route('test', 'test')
    config.add_route('formulaire_reglements', 'formulaire_reglements')
    config.add_route('getTownList', 'getTownList')
    config.add_route('getTopicsList', 'getTopicsList')
    config.add_route('createNewDocEntry', 'createNewDocEntry')
    config.add_route('document_ref', 'getDocumentReferences')
    config.add_route('legal_documents', 'getLegalDocuments')
    config.add_route('map', 'map')
    config.add_route('configpanel', 'configpanel')
    
    config.add_route('initjs', '/init.js')
    config.add_route('globalsjs', '/globals.js')

    config.add_route('ogcproxy', '/ogcproxy')
    
    # CLIENT VIEWS
    config.add_view('crdppf.views.entry.Entry', route_name = 'images')
    config.add_view('crdppf.views.entry.Entry', route_name='test')

    # Print proxy routes
    config.add_route('printproxy_report_get', '/printproxy/report/{ref}')
    config.add_route('printproxy_status', '/printproxy/status/{ref}.json')
    config.add_route('printproxy_report_create', '/printproxy/report/{type_}/{id}')

    #~ # ADMIN VIEWS
    #~ config.add_view('crdppf.views.administration.Config', route_name='configpanel')
    #~ config.add_view('crdppf.views.administration.Config', route_name='formulaire_reglements')

    config.add_route('catchall_static', '/*subpath')
    config.add_view('crdppf.static.static_view', route_name='catchall_static')
    
    config.scan()
Пример #54
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    # setup the database engine
    engine = engine_from_config(settings, 'sqlalchemy.', pool_size=5)
    sqlahelper.add_engine(engine)

    # initialize database structures
    initialize_db(engine)

    # set up beaker cache
    set_cache_regions_from_settings(settings)

    config = Configurator(settings=settings, root_factory=ACLFactory)

    # mako for templating
    config.include('pyramid_mako')

    # Mozilla Persona as the login verifier. It defines default
    # authentication and authorization policies.
    config.include('pyramid_persona')

    # override the authn policy to provide a callback
    secret = settings.get('persona.secret', None)
    authn_policy = AuthTktAuthenticationPolicy(secret,
                                               callback=groupfinder,
                                               hashalg='sha512')
    config.set_authentication_policy(authn_policy)

    # for json-encoded responses
    config.add_renderer('jsonp', JSONP(param_name='callback'))

    # for static assets
    config.add_static_view('static', 'xonstat:static')

    # robots
    config.add_route("robots", "robots.txt")
    config.add_view(robots, route_name="robots")

    # for 404s
    config.add_view(notfound, context=HTTPNotFound, renderer="404.mako")

    # ROOT ROUTE
    config.add_route("main_index", "/")
    config.add_view(main_index,
                    route_name="main_index",
                    renderer="main_index.mako")

    # MAIN SUBMISSION ROUTE
    config.add_route("submit_stats", "stats/submit")
    config.add_view(submit_stats, route_name="submit_stats")

    # PLAYER ROUTES
    config.add_route("player_game_index", "/player/{player_id:\d+}/games")
    config.add_view(player_game_index,
                    route_name="player_game_index",
                    renderer="player_game_index.mako")

    config.add_route("player_game_index_json",
                     "/player/{player_id:\d+}/games.json")
    config.add_view(player_game_index_json,
                    route_name="player_game_index_json",
                    renderer="jsonp")

    config.add_route("player_info", "/player/{id:\d+}")
    config.add_view(player_info,
                    route_name="player_info",
                    renderer="player_info.mako")

    config.add_route("player_info_json", "/player/{id:\d+}.json")
    config.add_view(player_info_json,
                    route_name="player_info_json",
                    renderer="jsonp")

    config.add_route("player_hashkey_info_text", "/player/me")
    config.add_view(player_hashkey_info_text,
                    route_name="player_hashkey_info_text",
                    renderer="player_hashkey_info_text.mako")

    config.add_route("player_hashkey_info_json", "/player/me.json")
    config.add_view(player_hashkey_info_json,
                    route_name="player_hashkey_info_json",
                    renderer="jsonp")

    config.add_route("player_elo_info_text", "/player/{hashkey}/elo.txt")
    config.add_view(player_elo_info_text,
                    route_name="player_elo_info_text",
                    renderer="player_elo_info_text.mako")

    config.add_route("players_elo", "/elo/{hashkeys}")
    config.add_view(players_elo, route_name="players_elo", renderer="jsonp")

    # FIXME - needs an additional method to convert to JSON
    config.add_route("player_elo_info_json", "/player/{hashkey}/elo.json")
    config.add_view(player_elo_info_json,
                    route_name="player_elo_info_json",
                    renderer="jsonp")

    config.add_route("player_accuracy", "/player/{id:\d+}/accuracy")
    config.add_view(player_accuracy_json,
                    route_name="player_accuracy",
                    renderer="jsonp")

    config.add_route("player_index", "/players")
    config.add_view(player_index,
                    route_name="player_index",
                    renderer="player_index.mako")

    config.add_route("player_index_json", "/players.json")
    config.add_view(player_index_json,
                    route_name="player_index_json",
                    renderer="jsonp")

    config.add_route("player_captimes", "/player/{player_id:\d+}/captimes")
    config.add_view(player_captimes,
                    route_name="player_captimes",
                    renderer="player_captimes.mako")

    config.add_route("player_captimes_json",
                     "/player/{player_id:\d+}/captimes.json")
    config.add_view(player_captimes_json,
                    route_name="player_captimes_json",
                    renderer="jsonp")

    config.add_route("player_weaponstats_data_json",
                     "/player/{id:\d+}/weaponstats.json")
    config.add_view(player_weaponstats_data_json,
                    route_name="player_weaponstats_data_json",
                    renderer="jsonp")

    config.add_route("top_players_by_time", "/topactive")
    config.add_view(top_players_by_time,
                    route_name="top_players_by_time",
                    renderer="top_players_by_time.mako")

    config.add_route("top_servers_by_players", "/topservers")
    config.add_view(top_servers_by_players,
                    route_name="top_servers_by_players",
                    renderer="top_servers_by_players.mako")

    config.add_route("top_maps_by_times_played", "/topmaps")
    config.add_view(top_maps_by_times_played,
                    route_name="top_maps_by_times_played",
                    renderer="top_maps_by_times_played.mako")

    # GAME ROUTES
    config.add_route("game_info", "/game/{id:\d+}")
    config.add_view(game_info,
                    route_name="game_info",
                    renderer="game_info.mako")

    config.add_route("game_info_json", "/game/{id:\d+}.json")
    config.add_view(game_info_json,
                    route_name="game_info_json",
                    renderer="jsonp")

    config.add_route("rank_index",
                     "/ranks/{game_type_cd:ctf|ffa|tdm|duel|ca|ft|race}")
    config.add_view(rank_index,
                    route_name="rank_index",
                    renderer="rank_index.mako")

    config.add_route("rank_index_json",
                     "/ranks/{game_type_cd:ctf|ffa|tdm|duel|ca|ft|race}.json")
    config.add_view(rank_index_json,
                    route_name="rank_index_json",
                    renderer="jsonp")

    config.add_route("game_index", "/games")
    config.add_view(game_finder,
                    route_name="game_index",
                    renderer="game_finder.mako")

    # SERVER ROUTES
    config.add_route("server_index", "/servers")
    config.add_view(server_index,
                    route_name="server_index",
                    renderer="server_index.mako")

    config.add_route("server_index_json", "/servers.json")
    config.add_view(server_index_json,
                    route_name="server_index_json",
                    renderer="jsonp")

    config.add_route("server_game_index",
                     "/server/{server_id:\d+}/games/page/{page:\d+}")
    config.add_view(server_game_index,
                    route_name="server_game_index",
                    renderer="server_game_index.mako")

    config.add_route("server_game_index_json",
                     "/server/{server_id:\d+}/games.json")
    config.add_view(server_game_index_json,
                    route_name="server_game_index_json",
                    renderer="jsonp")

    config.add_route("server_info", "/server/{id:\d+}")
    config.add_view(server_info,
                    route_name="server_info",
                    renderer="server_info.mako")

    config.add_route("server_info_json", "/server/{id:\d+}.json")
    config.add_view(server_info_json,
                    route_name="server_info_json",
                    renderer="jsonp")

    # MAP ROUTES
    config.add_route("map_index", "/maps")
    config.add_view(map_index,
                    route_name="map_index",
                    renderer="map_index.mako")

    config.add_route("map_index_json", "/maps.json")
    config.add_view(map_index_json,
                    route_name="map_index_json",
                    renderer="jsonp")

    config.add_route("map_info", "/map/{id:\d+}")
    config.add_view(map_info, route_name="map_info", renderer="map_info.mako")

    config.add_route("map_info_json", "/map/{id:\d+}.json")
    config.add_view(map_info_json,
                    route_name="map_info_json",
                    renderer="jsonp")

    config.add_route("map_captimes", "/map/{id:\d+}/captimes")
    config.add_view(map_captimes,
                    route_name="map_captimes",
                    renderer="map_captimes.mako")

    config.add_route("map_captimes_json", "/map/{id:\d+}/captimes.json")
    config.add_view(map_captimes_json,
                    route_name="map_captimes_json",
                    renderer="jsonp")

    # SEARCH ROUTES
    config.add_route("search", "search")
    config.add_view(search, route_name="search", renderer="search.mako")

    config.add_route("search_json", "search.json")
    config.add_view(search_json, route_name="search_json", renderer="jsonp")

    # ADMIN ROUTES
    config.add_forbidden_view(forbidden, renderer="forbidden.mako")

    config.add_route("login", "/login")
    config.add_view(login,
                    route_name="login",
                    check_csrf=True,
                    renderer="json")

    config.add_route("merge", "/admin/merge")
    config.add_view(merge,
                    route_name="merge",
                    renderer="merge.mako",
                    permission="merge")

    return config.make_wsgi_app()
Пример #55
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.scan('raggregate.models')
    engine = engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)
    initialize_sql(engine)

    session_factory = pyramid_beaker.session_factory_from_settings(settings)

    template_static_asset = "{0}/static".format(settings['mako.directories'])
    settings['template_static_asset'] = template_static_asset

    config = Configurator(settings=settings)
    config.include('pyramid_tm')

    if 'solr.address' in settings:
        import sunburnt
        solr_conn = sunburnt.SolrInterface(settings['solr.address'])
        config.registry.solr_conn = solr_conn

    if 'twitter.app_key' in settings and 'twitter.app_secret' in settings:
        from twython import Twython
        app_twit = Twython(settings['twitter.app_key'],
                           settings['twitter.app_secret'])
        config.registry.app_twit = app_twit

    config.set_session_factory(session_factory)

    # @TODO: the name "mako.directories" implies this could be a list
    # right now we don't care. Someone should fix this.
    config.add_static_view('static', template_static_asset)
    config.add_static_view('user_imgs', settings['user.picture_upload_package'])
    config.add_static_view('section_imgs', settings['section.picture_upload_package'])

    config.add_route('home', '/')
    config.add_route('login', '/login')
    config.add_route('list', '/list')
    config.add_route('post', '/post')
    config.add_route('new_page', '/new_page')
    config.add_route('new_post', '/new_post')
    config.add_route('ban', '/ban')
    config.add_route('vote', '/vote/{way}')
    config.add_route('full', '/full/{sub_id}')
    config.add_route('epistle', '/messages/{box}')
    config.add_route('follow', '/follow')
    config.add_route('save', '/save')
    config.add_route('notify', '/notify')
    config.add_route('search', '/search')
    config.add_route('twit_sign', '/twit_sign')
    config.add_route('user_info', '/user_info')
    config.add_route('user_preferences', '/user_preferences')
    config.add_route('buttons', '/buttons')
    config.add_route('favicon', '/favicon.ico')
    config.add_route('atom_story', '/atom_story.xml')
    config.add_route('atom_self_story', '/atom_self_story.xml')
    config.add_route('atom_combined', '/atom_combined.xml')
    config.add_route('atom_comment', '/atom_comment.xml')
    config.add_route('section', '/section')
    config.add_route('motd', '/motd')
    config.add_route('sublist', '/sublist/{sub_title}')
    config.add_route('sublistc', '/sublist_create')
    config.add_route('lost_password', '/lost_password')

    config.add_subscriber(subscribers.ban, NewResponse)
    config.add_subscriber(subscribers.user_session_handler, BeforeRender)
    config.add_subscriber(subscribers.clear_per_request_session, NewRequest)
    config.add_subscriber(subscribers.clean_inputs, NewRequest)

    config.scan('raggregate.views')


    pyramid_beaker.set_cache_regions_from_settings(settings)

    return config.make_wsgi_app()
Пример #56
0
def includeme(config):
    """ This function returns a Pyramid WSGI application.
    """

    # update the settings object from the YAML application config file
    settings = config.get_settings()
    settings.update(yaml.load(file(settings.get('app.cfg'))))

    global srid
    global schema
    global parentschema
    global formalchemy_language
    global formalchemy_default_zoom
    global formalchemy_default_x
    global formalchemy_default_y
    global formalchemy_available_functionalities

    config.set_request_property(
        get_user_from_request, name='user', reify=True)

    # configure 'locale' dir as the translation dir for c2cgeoportal app
    config.add_translation_dirs('c2cgeoportal:locale/')

    # initialize database
    engine = sqlalchemy.engine_from_config(
        config.get_settings(),
        'sqlalchemy.')
    sqlahelper.add_engine(engine)
    config.include(pyramid_tm.includeme)

    # initialize the dbreflection module
    dbreflection.init(engine)

    # dogpile.cache configuration
    caching.init_region(settings['cache'])
    caching.invalidate_region()

    # bind the mako renderer to other file extensions
    config.add_renderer('.html', mako_renderer_factory)
    config.add_renderer('.js', mako_renderer_factory)

    # add the "geojson" renderer
    config.add_renderer('geojson', GeoJSON())

    # add decimal json renderer
    config.add_renderer('decimaljson', DecimalJSON())

    # add the "xsd" renderer
    config.add_renderer('xsd', XSD(
        sequence_callback=dbreflection._xsd_sequence_callback))

    # add the set_user_validator directive, and set a default user
    # validator
    config.add_directive('set_user_validator', set_user_validator)
    config.set_user_validator(default_user_validator)

    # add an OGCProxy view
    config.add_route(
        'ogcproxy', '/ogcproxy',
        custom_predicates=(ogcproxy_route_predicate,))
    config.add_view('papyrus_ogcproxy.views:ogcproxy', route_name='ogcproxy')

    # add routes to the mapserver proxy
    config.add_route(
        'mapserverproxy', '/mapserv_proxy',
        custom_predicates=(mapserverproxy_route_predicate,),
        pregenerator=MultiDomainPregenerator())

    # add routes to csv view
    config.add_route('csvecho', '/csv')

    # add routes to the echo service
    config.add_route('echo', '/echo')

    # add routes to the entry view class
    config.add_route('home', '/')
    config.add_route('viewer', '/viewer.js')
    config.add_route('edit', '/edit')
    config.add_route('edit.js', '/edit.js')
    config.add_route('routing', '/routing')
    config.add_route('routing.js', '/routing.js')
    config.add_route('loginform', '/login.html')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('loginchange', '/loginchange')
    config.add_route('testi18n', '/testi18n.html')
    config.add_route('apijs', '/api.js')
    config.add_route('xapijs', '/xapi.js')
    config.add_route('apihelp', '/apihelp.html')
    config.add_route('xapihelp', '/xapihelp.html')
    config.add_route('themes', '/themes')
    # permalink theme: recover the theme for generating custom viewer.js url
    config.add_route('permalinktheme', '/theme/*themes')

    # checker routes, Checkers are web services to test and assess that
    # the application is correctly functioning.
    # These web services are used by tools like (nagios).
    config.add_route('checker_main', '/checker_main')
    config.add_route('checker_viewer', '/checker_viewer')
    config.add_route('checker_edit', '/checker_edit')
    config.add_route('checker_edit_js', '/checker_edit_js')
    config.add_route('checker_api', '/checker_api')
    config.add_route('checker_xapi', '/checker_xapi')
    config.add_route('checker_printcapabilities', '/checker_printcapabilities')
    config.add_route('checker_pdf', '/checker_pdf')
    config.add_route('checker_fts', '/checker_fts')
    config.add_route('checker_wmscapabilities', '/checker_wmscapabilities')
    config.add_route('checker_wfscapabilities', '/checker_wfscapabilities')
    # collector
    config.add_route('check_collector', '/check_collector')

    # print proxy routes
    config.add_route('printproxy', '/printproxy')
    config.add_route('printproxy_info', '/printproxy/info.json')
    config.add_route('printproxy_create', '/printproxy/create.json')
    config.add_route('printproxy_get', '/printproxy/{file}.printout')

    # full text search routes
    config.add_route('fulltextsearch', '/fulltextsearch')

    # Access to raster data
    config.add_route('raster', '/raster')
    config.add_route('profile.csv', '/profile.csv')
    config.add_route('profile.json', '/profile.json')

    # shortener
    config.add_route('shortener_create', '/short/create')
    config.add_route('shortener_get', '/short/{ref}')

    # add routes for the "layers" web service
    config.add_route(
        'layers_count', '/layers/{layer_id:\\d+}/count',
        request_method='GET')
    config.add_route(
        'layers_metadata', '/layers/{layer_id:\\d+}/md.xsd',
        request_method='GET')
    config.add_route(
        'layers_read_many',
        '/layers/{layer_id:\\d+,?(\\d+,)*\\d*$}',
        request_method='GET')  # supports URLs like /layers/1,2,3
    config.add_route(
        'layers_read_one', '/layers/{layer_id:\\d+}/{feature_id}',
        request_method='GET')
    config.add_route(
        'layers_create', '/layers/{layer_id:\\d+}',
        request_method='POST')
    config.add_route(
        'layers_update', '/layers/{layer_id:\\d+}/{feature_id}',
        request_method='PUT')
    config.add_route(
        'layers_delete', '/layers/{layer_id:\\d+}/{feature_id}',
        request_method='DELETE')
    config.add_route(
        'layers_enumerate_attribute_values',
        '/layers/{layer_name}/values/{field_name}',
        request_method='GET')
    # there's no view corresponding to that route, it is to be used from
    # mako templates to get the root of the "layers" web service
    config.add_route('layers_root', '/layers/')

    # pyramid_formalchemy's configuration
    config.include('pyramid_formalchemy')
    config.include('fa.jquery')

    # define the srid, schema and parentschema
    # as global variables to be usable in the model
    srid = config.get_settings()['srid']
    schema = config.get_settings()['schema']
    parentschema = config.get_settings()['parentschema']
    settings = config.get_settings()
    formalchemy_default_zoom = get_setting(
        settings,
        ('admin_interface', 'map_zoom'), formalchemy_default_zoom)
    formalchemy_default_x = get_setting(
        settings,
        ('admin_interface', 'map_x'), formalchemy_default_x)
    formalchemy_default_y = get_setting(
        settings,
        ('admin_interface', 'map_y'), formalchemy_default_y)
    formalchemy_available_functionalities = get_setting(
        settings,
        ('admin_interface', 'available_functionalities'),
        formalchemy_available_functionalities)

    # scan view decorator for adding routes
    config.scan(ignore='c2cgeoportal.tests')

    config.registry.registerUtility(
        MultiDomainStaticURLInfo(), IStaticURLInfo)
    # add the static view (for static resources)
    config.add_static_view(
        'static', 'c2cgeoportal:static',
        cache_max_age=int(settings["default_max_age"])
    )
Пример #57
0
 def test_one_engine(self):
     e = sa.create_engine(self.db1.url)
     sqlahelper.add_engine(e)
     retrieved = sqlahelper.get_engine()
     self.assertIs(retrieved, e)