예제 #1
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    set_cache_regions_from_settings(settings)
    authentication_policy = AuthTktAuthenticationPolicy('seekrit',
                                                        callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()

    config = Configurator(settings=settings,
                          root_factory=RootFactory,
                          authentication_policy=authentication_policy,
                          authorization_policy=authorization_policy)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    config.set_session_factory(session_factory_from_settings(settings))
    config.add_mako_renderer('.html')

    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

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

    # Add static routes (required for static_path in Mako)
    config.add_static_view(name=settings.get('webassets.base_url'),
                           path='static')
    config.include(include_views)
    config.include(include_css)
    config.include(include_js)
    config.scan()
    return config.make_wsgi_app()
예제 #2
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)
    json_renderer = JSON()

    def dataframe_adapter(df, request):
        return df.to_dict(orient="records")

    json_renderer.add_adapter(DataFrame, dataframe_adapter)
    config.add_renderer('json', json_renderer)

    config.include('pyramid_jinja2')
    config.include('pyramid_tm')

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

    config.add_route('home', '/')
    config.add_route('about', '/about')
    config.add_route('search', '/search/{name}')
    config.add_route('dropdown', '/dropdown/{namekey}')

    config.scan()

    return config.make_wsgi_app()
예제 #3
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('cornice')
    config.include('pyramid_mako')

    json_renderer = JSON()
    def datetime_adapter(obj, request):
        return obj.strftime('%Y-%m-%d %H:%M:%S')
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)

    def dictable_adapter(obj, request):
        return obj.asdict()
    json_renderer.add_adapter(DictableModel, dictable_adapter)

    config.add_renderer('json', json_renderer)

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app()
예제 #4
0
def color_json_renderer():
    def adapter(color, request):
        return color.to_dict()

    json_renderer = JSON()
    json_renderer.add_adapter(Color, adapter)
    return json_renderer
예제 #5
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus(settings['sqlalchemy.url'])
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbConfig['url'] = settings['sqlalchemy.url']
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    Base.metadata.reflect(views=True, extend_existing=False)

    config = Configurator(settings=settings)
    # Add renderer for datetime objects
    json_renderer = JSON()
    json_renderer.add_adapter(datetime, datetime_adapter)
    json_renderer.add_adapter(Decimal, decimal_adapter)
    config.add_renderer('json', json_renderer)

    # Set up authentication and authorization
    includeme(config)
    config.set_root_factory(SecurityRoot)


    # Set the default permission level to 'read'
    config.set_default_permission('read')
    config.include('pyramid_tm')
    add_routes(config)
    config.scan()
    return config.make_wsgi_app()
예제 #6
0
def includeme(config):
    log.info('included: www.app')

    settings = config.get_settings()
    cookie_name = settings['app.cookie']

    provider_name = settings['data.provider.security']
    data = Data()
    provider = data.get_provider(provider_name)

    config.set_session_factory(SessionFactory(json, cookie_name))

    config.set_authentication_policy(AuthenticationPolicy())
    config.set_authorization_policy(AuthorizationPolicy(provider))

    # include json datetime renderer
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

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

    config.include('www.app.core')

    config.include('www.app.core.security')
    config.include('www.app.core.security.views')

    # config.include('www.app.core.session')

    config.include('www.app.core.data')

    config.scan()
예제 #7
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus(
        settings['sqlalchemy.url'])
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbConfig['url'] = settings['sqlalchemy.url']
    """ Configuration de la connexion à la BDD """
    # DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    Base.metadata.reflect(views=True)
    """ Configuration du serveur pyramid"""
    config = Configurator(settings=settings)
    # Add renderer for datetime objects
    json_renderer = JSON()
    json_renderer.add_adapter(datetime, datetime_adapter)
    json_renderer.add_adapter(date, date_adapter)
    json_renderer.add_adapter(Decimal, decimal_adapter)
    json_renderer.add_adapter(bytes, bytes_adapter)
    config.add_renderer('json', json_renderer)
    config.registry.dbmaker = scoped_session(sessionmaker(bind=engine))
    config.add_request_method(db, name='dbsession', reify=True)
    # Set up authentication and authorization

    config.set_root_factory(SecurityRoot)
    config.add_subscriber(add_cors_headers_response_callback, NewRequest)

    # Set the default permission level to 'read'
    config.set_default_permission('read')
    config.include('pyramid_tm')
    add_routes(config)
    config.scan()
    return config.make_wsgi_app()
예제 #8
0
def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')

    config.registry.db = DatabaseClient()
    config.registry.dvr = DVR()
    
    def db(request):
        return config.registry.db

    def dvr(request):
        return config.registry.dvr

    config.add_request_method(db, 'db', reify=True)
    config.add_request_method(dvr, 'dvr', reify=True)
    
    json_renderer = JSON()
    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(datetime.date, datetime_adapter)
    config.add_renderer('json', json_renderer)
    
    config.add_route('index', '/')
    config.add_route('recordings', 'recordings')
    config.add_route('recording', 'recording/{id}')
    config.add_route('delete_recording', 'delete_recording/{id}')
    config.add_route('skip_recording', 'skip_recording/{id}')
    config.add_route('enable_recording', 'enable_recording/{id}')
    config.add_route('season_passes', 'season_passes')
    config.add_route('add_season_pass', 'add_season_pass')
    config.add_route('search', 'search')
    config.scan('.views')
    return config.make_wsgi_app()
예제 #9
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['tm.commit_veto'] = 'pyramid_tm.default_commit_veto'
    session_factory = UnencryptedCookieSessionFactoryConfig(
        'pyrapostbinsession')
    config = Configurator(
        settings=settings,
        session_factory=session_factory,
    )
    config.include('pyramid_jinja2')
    config.include('pyramid_exclog')
    config.include('cornice')
    config.include('db')
    add_routes(config)
    add_views(config)

    # These modify the request to add db and user as methods, which once called are then reify values
    # subclassing/overriding the Request will be... problematic, as discovered the hard way
    config.add_request_method(callable=user,
                              name=None,
                              property=True,
                              reify=True)

    # This should add an adapter for types normally we don't wrap in JSON
    json_renderer = JSON()
    json_renderer.add_adapter(datetime.date, date_serializer)
    json_renderer.add_adapter(datetime.time, time_serializer)
    config.add_renderer('json', json_renderer)

    config.scan()
    return config.make_wsgi_app()
예제 #10
0
def includeme(config):
    """
	RPC loader for Pyramid
	"""
    global _do_xmlrpc, _do_jsonrpc
    cfg = config.registry.settings
    _do_xmlrpc = asbool(cfg.get('netprofile.rpc.xmlrpc', True))
    _do_jsonrpc = asbool(cfg.get('netprofile.rpc.jsonrpc', True))

    if _do_xmlrpc:
        config.include('pyramid_rpc.xmlrpc')
        config.add_xmlrpc_endpoint('api.xmlrpc', '/api/xmlrpc')
    if _do_jsonrpc:
        config.include('pyramid_rpc.jsonrpc')
        renderer = JSON()

        def _json_datetime(obj, req):
            if obj.tzinfo is None:
                obj = obj.replace(tzinfo=tzlocal())
            return obj.isoformat()

        renderer.add_adapter(dt.datetime, _json_datetime)
        renderer.add_adapter(dt.date, lambda obj, req: obj.isoformat())
        renderer.add_adapter(dt.time, lambda obj, req: obj.isoformat())
        renderer.add_adapter(ipaddr.IPv4Address, lambda obj, req: int(obj))
        renderer.add_adapter(decimal.Decimal, lambda obj, req: str(obj))
        config.add_renderer('jsonrpc', renderer)
        config.add_jsonrpc_endpoint('api.jsonrpc',
                                    '/api/jsonrpc',
                                    default_renderer='jsonrpc')

    config.scan()
예제 #11
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)

    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

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

    config.include('pyramid_jinja2')
    config.include('.models')
    config.include('.routes')
    config.set_authentication_policy(MixedTokenAuthenticationPolicy())
    config.set_authorization_policy(
        AlwaysPassAuthenticatedAuthorizationPolicy()
    )

    enabled_registration_modules = settings.get(
        'pydiditpyramidgateway.enabled_registration_modules'
    )
    if enabled_registration_modules is not None:
        enabled_registration_modules = config.maybe_dotted(
            enabled_registration_modules.split(',')
        )
        for module in enabled_registration_modules:
            config.include(module)

    config.scan()
    pydiditbackend.initialize(json.loads(settings['backend_settings']))
    return config.make_wsgi_app()
예제 #12
0
파일: __init__.py 프로젝트: k-wiens/Blah
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application. """


    config = Configurator(settings=settings)

    #set up beaker session
    session_factory = session_factory_from_settings(settings)
    config.set_session_factory(session_factory)


    # add security tweens
 #   config.add_tween('aws_demo.tweens.clickjacking.clickjacking_factory')
 #   config.add_tween('aws_demo.tweens.secure_headers.secure_headers_factory')

    config.registry['mailer'] = Mailer.from_settings(settings=settings)

    # modify the built in json renderer to serialize dates properly
    json_date_renderer = JSON()
    json_date_renderer.add_adapter(datetime.datetime, new_datetime_adapter)
    
    # set .html renderer to allow mako templating
    config.add_renderer('.html', 'pyramid.mako_templating.renderer_factory')
    config.add_renderer('.htm', 'pyramid.mako_templating.renderer_factory')
    config.add_renderer('json', json_date_renderer)
    
    config.add_static_view('static', 'static', cache_max_age=3600)

    # login / registration
    config.add_route('index_view', '/')


    config.scan()
    return config.make_wsgi_app()
예제 #13
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.add_jinja2_search_path('kfhlog:templates')

    renderer = JSON()
    renderer.add_adapter(datetime, lambda obj, request: obj.isoformat()+'Z')
    renderer.add_adapter(date, lambda obj, request: obj.isoformat())
    renderer.add_adapter(Enum, lambda obj, request: obj.name)
    renderer.add_adapter(Qso, lambda obj, request: obj.ext_to_dict())
    config.add_renderer('extjson', renderer)

    config.include('pyramid_rpc.xmlrpc')
    config.add_settings({'redis.sessions.client_callable': 'kfhlog.redis.get_redis_client'})
    config.include('pyramid_redis_sessions')

    config.include('pyramid_celery')
    config.configure_celery(global_config['__file__'])

    config.include('.models')
    config.include('.routes')
    config.include('.security')
    config.include('.redis')
    config.include('.userconfig')
    config.scan()
    return config.make_wsgi_app()
예제 #14
0
def main(global_config, **settings):
    """Return 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_jinja2')
    config.include('pyramid_debugtoolbar')
    config.add_route('home', '/')
    config.add_route('data', '/data')
    config.add_route('data_advanced', '/data_advanced')
    config.add_route('data_yadcf', '/data_yadcf')
    config.add_route('dt_110x', '/dt_110x')
    config.add_route('dt_110x_basic_column_search',
                     '/dt_110x_basic_column_search')
    config.add_route('dt_110x_advanced_column_search',
                     '/dt_110x_advanced_column_search')
    config.add_route('dt_110x_yadcf',
                     '/dt_110x_yadcf')
    config.scan()

    # only for advanced example
    json_renderer = JSON()
    json_renderer.add_adapter(date, date_adapter)
    config.add_renderer('json_with_dates', json_renderer)

    return config.make_wsgi_app()
예제 #15
0
def configure_custom_json_renderer(config):
    json_renderer = JSON()

    def decimal_adapter(obj, request):
        return str(obj)

    json_renderer.add_adapter(Decimal, decimal_adapter)
    config.add_renderer('json', json_renderer)
예제 #16
0
파일: json.py 프로젝트: silenius/amnesia
def includeme(config):
    ''' Pyramid includeme '''
    json_renderer = JSON(indent=4)

    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(datetime.date, datetime_adapter)

    config.add_renderer('json', json_renderer)
예제 #17
0
def includeme(config: pyramid.config.Configurator) -> None:
    """Initialize json and fast_json renderer."""
    config.add_renderer("json", JSON(indent=2, sort_keys=True))
    config.add_renderer("fast_json", JSON(serializer=fast_dumps))
    config.add_renderer("cornice_json",
                        CorniceRenderer(indent=2, sort_keys=True))
    config.add_renderer("cornice_fast_json",
                        CorniceRenderer(serializer=fast_dumps))
예제 #18
0
 def add_route_and_views(config):
     config.add_route('dbname', '/test/')
     config.add_view(get_timedelta,
                     route_name='dbname',
                     renderer='json')
     json_renderer = JSON()
     json_renderer.add_adapter(timedelta, timedelta_adapter_factory())
     config.add_renderer('json', json_renderer)
예제 #19
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    # memory tracker
    settings['memory_tracker'] = tracker.SummaryTracker()
    config = Configurator(settings=settings)
    config.include('.models')

    renderer = JSON()
    renderer.add_adapter(datetime.date, lambda obj, request: obj.isoformat())
    config.add_renderer('json', renderer)

    here = os.path.dirname(__file__)
    stats_filename = os.path.join(here, 'dist', 'entrypoints.json')
    if os.path.isfile(stats_filename):
        with open(stats_filename) as infile:
            stats = json.load(infile)
    else:
        stats = dict(
            entrypoints=dict(index=dict(assets=list()),
                             admin=dict(assets=list())))
    config.add_request_method(
        lambda r: stats,
        'webpack_entrypoints',
        reify=True
        )

    favicon_stats = os.path.join(here, 'dist', 'favicon-stats.json')
    if os.path.isfile(favicon_stats):
        with open(favicon_stats) as infile:
            iconstats = json.load(infile)
    else:
        iconstats = dict(html=list())
    config.add_request_method(
        lambda r: iconstats,
        'favicon_stats',
        reify=True
        )

    # FIXME make tests
    JWT_SECRET = os.environ.get('JWT_SECRET', 'secret')
    config.set_jwt_authentication_policy(JWT_SECRET,
                                         callback=groupfinder)

    authz_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy)

    config.include('.routes')

    # config.set_request_property is removed in pyramid > 1.9
    # config.set_request_property('.util.get_user', 'user', reify=True)

    config.add_request_method('.util.get_user', 'user', reify=True)
    application = config.make_wsgi_app()
    # add wsgi middleware here

    return application
예제 #20
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus(settings['sqlalchemy.url'])
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbConfig['url'] = settings['sqlalchemy.url']

    """ Configuration de la connexion à la BDD """
    # DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    Base.metadata.reflect(views=True)

    """ Configuration du serveur pyramid"""
    config = Configurator(settings=settings)
    # Add renderer for datetime objects
    json_renderer = JSON()
    json_renderer.add_adapter(datetime, datetime_adapter)
    json_renderer.add_adapter(date, date_adapter)
    json_renderer.add_adapter(Decimal, decimal_adapter)
    json_renderer.add_adapter(bytes, bytes_adapter)
    config.add_renderer('json', json_renderer)
    config.registry.dbmaker = scoped_session(sessionmaker(bind=engine))
    config.add_request_method(db, name='dbsession', reify=True)
    # Set up authentication and authorization

    config.set_root_factory(SecurityRoot)
    config.add_subscriber(add_cors_headers_response_callback, NewRequest)

    # Set the default permission level to 'read'
    config.set_default_permission('read')
    config.include('pyramid_tm')
    add_routes(config)
    config.scan()
    return config.make_wsgi_app()
예제 #21
0
파일: rpc.py 프로젝트: unikmhz/npui
def includeme(config):
    """
    RPC loader for Pyramid
    """
    global _do_xmlrpc, _do_jsonrpc
    cfg = config.registry.settings
    _do_xmlrpc = asbool(cfg.get('netprofile.rpc.xmlrpc', True))
    _do_jsonrpc = asbool(cfg.get('netprofile.rpc.jsonrpc', True))

    if _do_xmlrpc:
        config.include('pyramid_rpc.xmlrpc')
        config.add_xmlrpc_endpoint('api.xmlrpc', '/api/xmlrpc')
    if _do_jsonrpc:
        config.include('pyramid_rpc.jsonrpc')
        renderer = JSON()

        def _json_datetime(obj, req):
            if obj.tzinfo is None:
                obj = obj.replace(tzinfo=tzlocal())
            return obj.isoformat()

        renderer.add_adapter(dt.datetime, _json_datetime)
        renderer.add_adapter(dt.date, lambda obj, req: obj.isoformat())
        renderer.add_adapter(dt.time, lambda obj, req: obj.isoformat())
        renderer.add_adapter(ipaddress.IPv4Address, lambda obj, req: int(obj))
        renderer.add_adapter(decimal.Decimal, lambda obj, req: str(obj))
        config.add_renderer('jsonrpc', renderer)
        config.add_jsonrpc_endpoint('api.jsonrpc', '/api/jsonrpc',
                                    default_renderer='jsonrpc')

    config.scan()
예제 #22
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
    init_model()

    session_factory = session_factory_from_settings(settings)
    if 'localization' not in settings:
        settings['localization'] = 'id_ID.UTF-8'
    locale.setlocale(locale.LC_ALL, settings['localization'])        
    if 'timezone' not in settings:
        settings['timezone'] = DefaultTimeZone
    config = Configurator(settings=settings,
                          root_factory='reklame.models.RootFactory',
                          session_factory=session_factory)
    config.include('pyramid_beaker')                          
    config.include('pyramid_chameleon')

    authn_policy = AuthTktAuthenticationPolicy('sosecret',
                    callback=group_finder, hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()                          
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.add_request_method(get_user, 'user', reify=True)
    config.add_request_method(get_title, 'title', reify=True)
    config.add_notfound_view(RemoveSlashNotFoundViewFactory())        
                          
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('deform_static', 'deform:static')
    config.add_static_view('files', settings['static_files'])    
    ############################################################################
    config.include('pyramid_rpc.jsonrpc') # JSON RPC
    json_renderer = JSON()
    json_renderer.add_adapter(datetime.datetime, lambda v, request: v.isoformat())
    json_renderer.add_adapter(datetime.date, lambda v, request: v.isoformat())
    config.add_renderer('myjson', json_renderer)
    config.add_jsonrpc_endpoint('ws_reklame', '/ws/reklame', default_renderer="myjson")       
    ############################################################################
 
    routes = DBSession.query(Route.kode, Route.path, Route.nama).all()
    for route in routes:
        config.add_route(route.kode, route.path)
        if route.nama:
            titles[route.kode] = ' - '.join([main_title, route.nama])     
            
    
    config.scan()
    
    app = config.make_wsgi_app()
    from paste.translogger import TransLogger
    app = TransLogger(app, setup_console_handler=False)    
    return app
예제 #23
0
def includeme(config):
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)

    def uuid_adapter(obj, request):
        return str(obj)
    json_renderer.add_adapter(uuid.UUID, uuid_adapter)

    config.add_renderer('json', json_renderer)
예제 #24
0
def patch_json_renderer():
    """ Returns a patched JSON renderer capable of serializing custom
    objects.
    """

    def datetime_adapter(obj, request):
        return int(obj.strftime('%s'))

    renderer = JSON()
    renderer.add_adapter(datetime.datetime, datetime_adapter)

    return renderer
예제 #25
0
def modify(config):
    from pyramid.renderers import JSON
    from datetime import datetime

    # override: json renderer
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

    json_renderer.add_adapter(datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)
예제 #26
0
def main(global_config, **settings):
    """ 
    This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.add_static_view('static', 'static', cache_max_age=3600)

    # Use jinja2 as templating language
    config.include('pyramid_jinja2')

    # Add a datetime json renderer adapter.
    # This snippet comes from:
    # http://docs.pylonsproject.org/projects/pyramid/en/master/narr/renderers.html#using-the-add-adapter-method-of-a-custom-json-renderer
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

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

    # (route_name, URL)
    config.add_route('upcoming_events', 'api/v1.0/events')
    config.add_route('home_page', '/')
    config.add_route('events_view', 'events')
    config.add_route('update_building_alias', 'api/v1.0/update_building_alias')
    config.scan()

    # db_url is stored in .ini files
    db_url = urlparse(settings['mongo_uri'])

    # The registry "maps resource types to views, as well as housing
    # other application-specific component registrations"
    config.registry.db = MongoClient(host=db_url.hostname)

    # TODO figure out what these do. Taken from Pyramid/mongo tutorial here:
    # http://pyramid-cookbook.readthedocs.org/en/latest/database/mongodb.html
    def add_db(request):
        db = config.registry.db[db_url.path[1:]]
        if db_url.username and db_url.password:
            print('authenitacintg?')
            db.authenticate(db_url.username, db_url.password)
        return db

    def add_fs(request):
        print('adding_fs??')
        return GridFS(request.db)

    config.add_request_method(add_db, 'db', reify=True)
    config.add_request_method(add_fs, 'fs', reify=True)

    return config.make_wsgi_app()
예제 #27
0
def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    session_factory = sessionmaker(bind=engine)
    settings['db.session_factory'] = session_factory

    config = Configurator(
        settings=settings,
        request_factory=RequestWithDB
    )

    json_renderer = JSON()
    json_renderer.add_adapter(datetime.date, date_adapter)
    json_renderer.add_adapter(decimal.Decimal, decimal_adapter)
    config.add_renderer('json', json_renderer)

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

    # GET    /api/exploracaos      = Return all exploracaos
    # POST   /api/exploracaos      = Create a new exploracao, 'exp_id' in body
    # GET    /api/exploracaos/{id} = Return individual exploracao
    # PUT    /api/exploracaos/{id} = Update exploracao
    # DELETE /api/exploracaos/{id} = Delete exploracao
    config.add_route('exploracaos',     '/api/exploracaos')
    config.add_route('exploracaos_id',  '/api/exploracaos/{id}')

    # GET    /api/utentes      = Return all utentes
    # POST   /api/utentes      = Create a new utente, 'nome' in body
    # GET    /api/utentes/{id} = Return individual utente
    # PUT    /api/utentes/{id} = Update utente
    # DELETE /api/utentes/{id} = Delete utente
    config.add_route('utentes', '/api/utentes')
    config.add_route('utentes_id', '/api/utentes/{id}')

    # GET    /api/cultivos      = Return all cultivos
    # PUT    /api/utentes/{id} = Update cultivo
    config.add_route('cultivos', '/api/cultivos')
    config.add_route('cultivos_id', '/api/cultivos/{id}')

    # GET    /api/settings      = Return all settings
    # PUT    /api/settings/{property} = Update property
    config.add_route('settings', '/api/settings')
    config.add_route('settings_property', '/api/settings/{property}')

    # GET /domains = Return all domains (utentes included)
    config.add_route('domains', '/api/domains')

    # GET /api/base/fountains = Return a GeoJSON
    # POST /api/base/fountains = DELETE the table and insert the features in the zip
    config.add_route('base_fountains', '/api/base/fountains')

    config.scan()
    return config.make_wsgi_app()
예제 #28
0
def main(global_config, **settings):
    """ 
    This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.add_static_view('static', 'static', cache_max_age=3600)

    # Use jinja2 as templating language
    config.include('pyramid_jinja2')

    # Add a datetime json renderer adapter.
    # This snippet comes from:
    # http://docs.pylonsproject.org/projects/pyramid/en/master/narr/renderers.html#using-the-add-adapter-method-of-a-custom-json-renderer
    json_renderer = JSON()
    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)

    # (route_name, URL)
    config.add_route('upcoming_events', 'api/v1.0/events')
    config.add_route('home_page', '/')
    config.add_route('events_view', 'events')
    config.add_route('update_building_alias', 'api/v1.0/update_building_alias')
    config.scan()

    # db_url is stored in .ini files 
    db_url = urlparse(settings['mongo_uri'])

    # The registry "maps resource types to views, as well as housing 
    # other application-specific component registrations"
    config.registry.db = MongoClient(
            host=db_url.hostname
    )

    # TODO figure out what these do. Taken from Pyramid/mongo tutorial here:
    # http://pyramid-cookbook.readthedocs.org/en/latest/database/mongodb.html
    def add_db(request):
      db = config.registry.db[db_url.path[1:]]
      if db_url.username and db_url.password:
        print('authenitacintg?')
        db.authenticate(db_url.username, db_url.password)
      return db

    def add_fs(request):
      print('adding_fs??')
      return GridFS(request.db)

    config.add_request_method(add_db, 'db', reify=True)
    config.add_request_method(add_fs, 'fs', reify=True)

    return config.make_wsgi_app()
예제 #29
0
def make_app(settings):
    config = Configurator(settings=settings)
    config.include("app.routes")

    # override: json renderer
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)

    return config.make_wsgi_app()
예제 #30
0
파일: config.py 프로젝트: limnid/py-s3
def configure_project(config):
    def datetime_adapter(obj, request):
        return obj.isoformat()

    json_renderer = JSON()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)

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

    from s3.routes import project_routes
    config.include(project_routes)
    config.add_tween('s3.tweens.timing_tween_factory')
예제 #31
0
def make_app(settings):
    config = Configurator(settings=settings)
    config.include("app.routes")

    # override: json renderer
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

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

    return config.make_wsgi_app()
예제 #32
0
def configure_renderers(config):
    json_renderer = JSON()
    json_renderer.add_adapter(Customer, lambda p, _: p.__dict__)
    config.add_renderer('json', json_renderer)
    config.add_renderer('vcard', VCardRenderer())
    config.add_renderer('img', GravatarRenderer())

    mappings = {
        'application/json': json_renderer,
        'text/vcard': VCardRenderer(),
        'image/png': GravatarRenderer()
    }
    negotiator = NegotiatingRenderer(mappings)
    config.add_renderer('negotiate', negotiator)
예제 #33
0
def custom_json_renderer():
    """
    Return a custom json renderer that can deal with some datetime objects.
    """


    def datetime_adapter(obj, request):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        raise TypeError ("DateTime is not serializable")


    def time_adapter(obj, request):
        if isinstance(obj, datetime.date):
            return str(obj)
        raise TypeError ("Time is not serializable")


    def decimal_adapter(obj, request):
        if isinstance(obj, decimal.Decimal):
            return float("{0:.2f}".format(obj))
        raise TypeError ("Decimal not serializable")


    json_renderer = JSON()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(datetime.date, time_adapter)
    json_renderer.add_adapter(datetime.time, time_adapter)
    json_renderer.add_adapter(decimal.Decimal, decimal_adapter)
    return json_renderer
예제 #34
0
def custom_json_renderer():
    """
    Return a custom json renderer that can deal with some datetime objects.
    """
    def datetime_adapter(obj, request):
        return obj.isoformat()

    def time_adapter(obj, request):
        return str(obj)

    json_renderer = JSON()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(datetime.time, time_adapter)
    return json_renderer
예제 #35
0
def includeme(config):
    log.info('including: saas.app.core')

    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

    json_renderer.add_adapter(datetime.datetime, datetime_adapter)

    def time_adapter(obj, request):
        return obj.isoformat()

    json_renderer.add_adapter(datetime.time, time_adapter)

    def decimal_adapter(obj, request):
        return str(obj)

    json_renderer.add_adapter(decimal.Decimal, decimal_adapter)

    config.add_renderer('json', json_renderer)

    config.include('saas.app.core.services')
    config.include('saas.app.core.stores')
    config.include('saas.app.core.views')
    config.include('saas.app.core.views.api')

    config.include('saas.app.core.modules.global')
    config.include('saas.app.core.modules.user')

    config.include('saas.app.modules.common')
    config.include('saas.app.modules.admin')
예제 #36
0
def SetupJSONRenderer(pyramid_config):
    """
    Extend the default pyramid json renderer with support for datetime and file storage
    objects. Call `SetupJSONRenderer` in the main function e.g. ::

        config = Configurator(root_factory = getRoot, settings = settings)
        SetupJSONRenderer(config)
        config.include('pyramid_chameleon')

    :param pyramid_config:
    :return:
    """
    json_renderer = JSON()

    def datetimeAdapter(obj, request):
        return obj.isoformat()

    json_renderer.add_adapter(datetime, datetimeAdapter)

    def fileStorageAdapter(obj, request):
        file = {}
        file["filekey"] = obj.filekey
        file["filename"] = obj.filename
        file["size"] = obj.size
        return file

    json_renderer.add_adapter(IFileStorage, fileStorageAdapter)

    def confAdapter(obj, request):
        return DumpJSONConf(obj)

    json_renderer.add_adapter(baseConf, confAdapter)

    pyramid_config.add_renderer('json', json_renderer)
예제 #37
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus(
        settings['sqlalchemy.url'])
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbConfig['url'] = settings['sqlalchemy.url']
    dbConfig['siteName'] = settings['siteName']
    dbConfig['mail'] = settings['smtpMail']
    dbConfig['pwd'] = settings['smtpPwd']
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    Base.metadata.reflect(views=True, extend_existing=False)

    config = Configurator(settings=settings)
    # Add renderer for datetime objects
    json_renderer = JSON()
    json_renderer.add_adapter(datetime, datetime_adapter)
    json_renderer.add_adapter(Decimal, decimal_adapter)
    json_renderer.add_adapter(bytes, bytes_adapter)
    config.add_renderer('json', json_renderer)

    # Set up authentication and authorization
    includeme(config)
    config.set_root_factory(SecurityRoot)

    config.add_subscriber(add_cors_headers_response_callback, NewRequest)
    # Set the default permission level to 'read'
    config.set_default_permission('read')
    config.include('pyramid_tm')
    add_routes(config)
    config.scan()
    return config.make_wsgi_app()
예제 #38
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('custom_object', '/custom_object.json')

    json_third_party = JSON()
    json_third_party.add_adapter(ThirdPartyObject, third_party_adapter)
    config.add_renderer('json_third_party', json_third_party)
    config.add_route('third_party', '/third_party.json')

    config.scan()
    return config.make_wsgi_app()
예제 #39
0
def do_config(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    load_project_settings()

    session_factory = SignedCookieSessionFactory(
        settings.get('session.secret', 'hello'))

    config = Configurator(session_factory=session_factory, settings=settings)
    config.add_renderer('prettyjson', JSON(indent=4))
    config.include('pyramid_mako')
    config.add_view('pyramid.view.append_slash_notfound_view',
                    context='pyramid.httpexceptions.HTTPNotFound')

    # ArangoDB configuration
    graph_models.connect(server=settings['gdb.server'],
                         port=settings['gdb.port'],
                         username=settings['gdb.username'],
                         password=settings['gdb.password'],
                         db_name=settings['gdb.database'])

    application_routes(config)
    config.scan()

    return config
예제 #40
0
 def render(self, things, adapters=()):
     """Manually call the renderer and pass in the adapters.
     Adapters get passed in because the component registry is scoped
     to the test case.
     """
     renderer = JSON(adapters=adapters)
     return renderer(things)(things, {})
예제 #41
0
def json_data_adapter(config):
    json_renderer = JSON()
    add_adapters(json_renderer)

    config.add_renderer('json', json_renderer)
    config.add_renderer('cornicejson', FuretUIRender())
    config.add_renderer('pyramid_rpc:jsonrpc', json_renderer)
예제 #42
0
def main(global_config, **settings):
    """ This function returns a WSGI application.
    """
    config = Configurator(settings=settings)
    config.add_renderer('utf8_json', JSON(ensure_ascii=False))
    add_view(config)

    # MongoDB
    def add_mongo_db(event):
        settings = event.request.registry.settings
        url = settings['mongodb.url']
        db_name = settings['mongodb.db_name']
        db = settings['mongodb_conn'][db_name]
        event.request.db = db

    db_uri = settings['mongodb.url']
    MongoDB = pymongo.Connection
    if 'pyramid_debugtoolbar' in set(settings.values()):
        class MongoDB(pymongo.Connection):
            def __html__(self):
                return 'MongoDB: <b>{}></b>'.format(self)

    conn = MongoDB(db_uri)
    config.registry.settings['mongodb_conn'] = conn
    config.add_subscriber(add_mongo_db, NewRequest)
    config.scan('albumapp')
    return config.make_wsgi_app()
예제 #43
0
def main(global_config, **settings):
    with Configurator(settings=settings) as config:

        def bytes_adapter(obj, request):
            return base64.b64encode(obj).decode()

        json_renderer = JSON(indent=4)
        json_renderer.add_adapter(bytes, bytes_adapter)

        config.add_renderer('json', json_renderer)
        config.include('ns_portal.database')
        config.include('ns_portal.core')
        config.include('ns_portal.routes')
        config.include('ns_portal.utils')

    return config.make_wsgi_app()
예제 #44
0
파일: __init__.py 프로젝트: HaideiGV/loader
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.add_renderer('img_json', JSON(indent=4))
    config.add_static_view('static', 'static', cache_max_age=3600)

    db_url = urlparse("mongodb://*****:*****@localhost:27017/loaddb")

    config.registry.db = MongoClient(
        host=db_url.hostname,
        port=db_url.port,
    )

    def add_db(request):
        db = config.registry.db[db_url.path[1:]]
        if db_url.username and db_url.password:
            db.authenticate(db_url.username, db_url.password)
        return db

    config.add_route('index', '/')
    config.add_request_method(add_db, 'db', reify=True)

    user_resource = resource.add_resource(File,
                                          collection_path='/api/v1/files',
                                          path='/api/v1/files/{uuid}')

    config.include("cornice")
    config.add_cornice_resource(user_resource)
    config.scan('loader')
    return config.make_wsgi_app()
예제 #45
0
def main(global_config, **settings):

    # Initialize database connection and schema
    db_connection_string = settings.get("connection_sring",
                                        "sqlite:///db.sqlite")
    db.initialize(db_connection_string)

    config = Configurator(settings=settings)

    # Automatically commit db transaction on 2xx/3xx response and rollback
    # transaction on 4xx/5xx response or when an exception is raised
    config.include('pyramid_tm')

    # make JSON pretty
    config.add_renderer('json', JSON(indent=4))

    # Routes
    config.add_route('root', '/api', request_method='GET')
    config.add_route('get_quiz_questions', '/api/question', request_method='GET')
    config.add_route('get_create_question_data', '/api/submit', request_method='GET')
    config.add_route('submit_question', '/api/submit', request_method='POST')

    # Views
    config.scan('questionmaster.views');

    # Static content
    config.add_static_view("", "static")

    return config.make_wsgi_app()
예제 #46
0
def main(*args, **settings):
    from pyramid.config import Configurator
    from pyramid.events import NewRequest, ContextFound
    from pyramid.authentication import BasicAuthAuthenticationPolicy
    from pyramid.authorization import ACLAuthorizationPolicy
    from pyramid.renderers import JSON, JSONP

    logger.info('Start registry api...')
    read_users(settings['auth.file'])
    config = Configurator(autocommit=True,
                          settings=settings,
                          authentication_policy=BasicAuthAuthenticationPolicy(
                              auth_check, __name__),
                          authorization_policy=ACLAuthorizationPolicy(),
                          root_factory=Root,
                          route_prefix=ROUTE_PREFIX)

    config.include('pyramid_exclog')
    config.add_forbidden_view(forbidden)
    config.add_request_method(request_params, 'params', reify=True)
    config.add_request_method(authenticated_role, reify=True)
    config.add_renderer('prettyjson', JSON(indent=4))
    config.add_renderer('jsonp', JSONP(param_name='opt_jsonp'))
    config.add_renderer('prettyjsonp', JSONP(indent=4, param_name='opt_jsonp'))
    config.add_subscriber(add_logging_context, NewRequest)
    config.add_subscriber(set_logging_context, ContextFound)
    config.add_subscriber(set_renderer, NewRequest)
    config.add_route('health', '/health')
    config.add_route('registry', '/registry/{param}.json')
    config.scan('openprocurement.medicines.registry.api.views')
    return config.make_wsgi_app()
예제 #47
0
 def setUp(self):
     from pyramid.renderers import JSON
     json_renderer = JSON()
     settings = {
         'pyramlson.apidef_path': os.path.join(DATA_DIR, 'test-api.raml'),
         'pyramlson.debug': 'true',
         'pyramlson.arguments_transformation_callback': inflection.underscore,
         'pyramlson.convert_parameters': 'true'
     }
     self.config = testing.setUp(settings=settings)
     self.config.include('pyramlson')
     json_renderer.add_adapter(datetime, datetime_adapter)
     self.config.add_renderer('json', json_renderer)
     self.config.scan('.resource')
     from webtest import TestApp
     self.testapp = TestApp(self.config.make_wsgi_app())
예제 #48
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.add_translation_dirs('locale/')

    # Custom JSON renderer
    json_renderer = JSON()
    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)

    def objectid_adapter(obj, request):
        return unicode(obj)
    json_renderer.add_adapter(bson.objectid.ObjectId, objectid_adapter)

    config.add_renderer('json', json_renderer)

    config.include('pyramid_jinja2')
    config.add_renderer('.html', 'pyramid_jinja2.renderer_factory')
    config.add_jinja2_search_path("billwatcher:templates")

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

    db_url = urlparse(settings['mongo_uri'])
    config.registry.db = pymongo.Connection(
        host=db_url.hostname,
        port=db_url.port
    )

    def add_db(request):
        db = config.registry.db[db_url.path[1:]]
        if db_url.username and db_url.password:
            db.authenticate(db_url.username, db_url.password)
        return db

    def add_fs(request):
        return GridFS(request.db)

    config.add_request_method(add_db, 'db', reify=True)
    config.add_request_method(add_fs, 'fs', reify=True)
        
    config.include('billwatcher.views.views_include')
    config.scan()
    return config.make_wsgi_app()
예제 #49
0
def main (global_config, **settings):
	""" This function returns a Pyramid WSGI application.
	"""
	sapyens.helpers.set_utc_timezone()

	engine = engine_from_config(settings, 'sqlalchemy.')
	boardless.db.init(engine, settings)

	config = Configurator(
			settings = settings,
			root_factory = RootFactory,
			session_factory = pyramid.session.SignedCookieSessionFactory(
				# The secret should be at least as long as the block size of the selected hash algorithm. For sha512 this would mean a 128 bit (64 character) secret.
				# For sha512 this would mean a 128 bit (64 character) secret
				secret = 'sETbVPAqkZxJTneqWpgnczyGhuwtfHNYMFZUMVwRjDiIRuSKGzdymHNBjDatQlhr',
				hashalg = 'sha512',
				cookie_name = 'boardless.session',
				timeout = 60 * 60 * 24 * 3, # A number of seconds of inactivity before a session times out. If None then the cookie never expires
				max_age = 60 * 60 * 24 * 3, # The maximum age of the cookie used for sessioning (in seconds). Default: None (browser scope).
				domain = settings.get('cookie_domain', '.boardless.com'), # TODO
				set_on_exception = True, # If True, set a session cookie even if an exception occurs while rendering a view
			),
			authentication_policy = pyramid.authentication.SessionAuthenticationPolicy(
				callback = get_identifiers,
				debug = False
			),
			authorization_policy = pyramid.authorization.ACLAuthorizationPolicy(),
	)

	# Mailer
	config.include('pyramid_mailer')

	json_renderer = JSON()
	json_renderer.add_adapter(decimal.Decimal, h.decimal_json_encoder)

	config.add_renderer('json', json_renderer)
	config.set_request_property(h.get_user, 'user')
	config.add_static_view('static', 'static', cache_max_age = 3600)
	config.scan(boardless.views)

	# Recreate the pool to close left connections (e.g. after reflection)
	# It prevents connection sharing between later-forked server workers (e.g. gunicorn with preload_app)
	DBSession.remove()
	engine.dispose()

	return config.make_wsgi_app()
예제 #50
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_sqlalchemy')
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)
    initialization.initialize(config)

    config.scan()
    app = config.make_wsgi_app()
    return install_middlewares(app, settings)
예제 #51
0
def main(global_config, **settings):
    """Return 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_jinja2")

    config.include("pyramid_debugtoolbar")

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

    config.add_route("data", "/data")

    config.add_route("data_advanced", "/data_advanced")

    config.add_route("data_yadcf", "/data_yadcf")

    config.add_route("dt_110x", "/dt_110x")

    config.add_route("dt_110x_custom_column", "/dt_110x_custom_column")

    config.add_route("dt_110x_basic_column_search",
                     "/dt_110x_basic_column_search")

    config.add_route("dt_110x_advanced_column_search",
                     "/dt_110x_advanced_column_search")

    config.add_route("dt_110x_yadcf", "/dt_110x_yadcf")

    config.scan()

    json_renderer = JSON()

    json_renderer.add_adapter(date, date_adapter)

    config.add_renderer("json_with_dates", json_renderer)

    config.add_jinja2_renderer('.html')

    return config.make_wsgi_app()
예제 #52
0
def SetupJSONRenderer(pyramid_config):
    """
    Extend the default pyramid json renderer with support for datetime and file storage
    objects. Call `SetupJSONRenderer` in the main function e.g. ::

        config = Configurator(root_factory = getRoot, settings = settings)
        SetupJSONRenderer(config)
        config.include('pyramid_chameleon')

    :param pyramid_config:
    :return:
    """
    json_renderer = JSON()

    def datetimeAdapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime, datetimeAdapter)

    def fileStorageAdapter(obj, request):
        file = {}
        file["filekey"] = obj.filekey
        file["filename"] = obj.filename
        file["size"] = obj.size
        return file
    json_renderer.add_adapter(IFileStorage, fileStorageAdapter)

    def confAdapter(obj, request):
        return DumpJSONConf(obj)
    json_renderer.add_adapter(baseConf, confAdapter)

    pyramid_config.add_renderer('json', json_renderer)
예제 #53
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['sqlalchemy.url'] = settings['cn.dialect'] + quote_plus(settings['sqlalchemy.url'])
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbConfig['data_schema'] = settings['data_schema']
    dbConfig['sensor_schema'] = settings['sensor_schema']
    dbConfig['url'] = settings['sqlalchemy.url']
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    Base.metadata.reflect(views=True, extend_existing=False)
    authn_policy = AuthTktAuthenticationPolicy(
        settings['auth.secret'],
        cookie_name='ecoReleve-Core',
        callback=role_loader,
        hashalg='sha512',
        max_age=86400)
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings)
    
    # Add renderer for datetime objects
    json_renderer = JSON()
    json_renderer.add_adapter(datetime, datetime_adapter)
    json_renderer.add_adapter(Decimal, decimal_adapter)
    config.add_renderer('json', json_renderer)
    
    # Add renderer for CSV files.
    config.add_renderer('csv', CSVRenderer)
    config.add_renderer('pdf', PDFrenderer)
    config.add_renderer('gpx', GPXRenderer)
    
    # Set up authentication and authorization
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.set_root_factory(SecurityRoot)
    # Set the default permission level to 'read'
    config.set_default_permission('read')
    
    config.include('pyramid_tm')
    #config.set_request_factory(request_factory)
    add_routes(config)
    #add_views(config)
    config.scan()
    return config.make_wsgi_app()
예제 #54
0
def main(global_config, **settings):
	""" This function returns a Pyramid WSGI application.
	"""

	const.update_cache_values()

	# set mako default filters
	settings['mako.imports'] = ['from markupsafe import escape_silent']
	settings['mako.default_filters'] = ['escape_silent']

	config = Configurator(settings=settings, root_factory='cioc.core.rootfactories.BasicRootFactory',
					request_factory='cioc.core.request.CiocRequest')
	json_renderer = JSON()
	json_renderer.add_adapter(datetime.datetime, datetime_adapter)
	json_renderer.add_adapter(datetime.date, datetime_adapter)
	json_renderer.add_adapter(Decimal, decimal_adapter)
	config.add_renderer('json', json_renderer)

	# allow for multiple templated css files with the which match parameter
	config.add_route('template_css', 'styles/d/{version}/cioc{which:[^_]+}_{templateid:\d+}{debug:(_debug)?}.css',
				factory='cioc.core.rootfactories.AllowSSLRootFactory')
	config.add_route('jquery_icons', 'styles/d/{version}/images/ui-icons_{colour:[0-9a-zA-Z]{6}}_256x240.png',
				factory='cioc.core.rootfactories.AllowSSLRootFactory')

	config.add_static_view('styles', 'cioc:styles')
	config.add_static_view('scripts', 'cioc:scripts')
	config.add_static_view('images', 'cioc:images')

	config.add_route('cic_recentsearch', 'recentsearch', factory='cioc.web.recentsearch.RecentSearchRootFactory')
	config.add_route('vol_recentsearch', 'volunteer/recentsearch', factory='cioc.web.recentsearch.RecentSearchRootFactory')

	config.add_view('pyramid.view.append_slash_notfound_view',
				context='pyramid.httpexceptions.HTTPNotFound')

	config.include('cioc.web.admin')
	config.include('cioc.web.cic')
	config.include('cioc.web.gbl')
	config.include('cioc.web.stats')
	config.include('cioc.web.ct')
	config.include('cioc.web.export')
	config.include('cioc.web.import_')
	config.include('cioc.web.offline')
	config.include('cioc.web.special')
	config.include('cioc.web.vol')
	config.include('cioc.web.rpc')
	config.include('cioc.web.jsonfeeds')
	config.include('cioc.core.xmlrenderer')

	config.add_subscriber(on_context_found, 'pyramid.events.ContextFound')

	config.add_view(notfound_view, context=URLDecodeError)

	if asbool(settings.get('show_db_warning_page')):
		config.add_view(connection_error, context='cioc.core.connection.ConnectionError', renderer='cioc.web:templates/dberror.mak')

	config.scan()
	config.scan('cioc.core', ignore='cioc.core.tests')

	return config.make_wsgi_app()
예제 #55
0
파일: __init__.py 프로젝트: mdargan/weather
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)
    json_renderer = JSON()
    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(datetime.date, datetime_adapter)
    config.add_renderer('json_custom', json_renderer)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan(ignore='src.cron')
   
    return config.make_wsgi_app()
예제 #56
0
파일: __init__.py 프로젝트: aagusti/e-sppt
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

    OtherEngine = engine_from_config(settings, 'othersql.')
    OtherEngine.echo=False
    OtherDBSession.configure(bind=OtherEngine)
    OtherBase.metadata.bind = OtherEngine
    
    os_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    
    config = Configurator(settings=settings, session_factory = os_session_factory)
    
    config.include('pyramid_chameleon')
    
    json_renderer = JSON()
    def datetime_adapter(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)
    
    #config.add_renderer('json', JSON(indent=0))    
    
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('deform_static', 'deform:static')

    config.add_route('home', '/home')
    config.add_route('login', '/')
    config.add_route('login_it', '/login_it')
    config.add_route('logout', '/logout')
    config.add_route('lupa', '/lupa')
    config.add_route('change', '/change')

    add_route(config, esppt_route)
 
    config.scan()
    
    return config.make_wsgi_app()
예제 #57
0
파일: __init__.py 프로젝트: Azula/votabo
def configure_templates(config):
    # json settings
    from pyramid.renderers import JSON
    from sqlalchemy.orm.query import Query

    json_renderer = JSON()
    def query_adapter(obj, request):
        return list(obj)
    json_renderer.add_adapter(Query, query_adapter)

    config.add_renderer('json', json_renderer)

    # CSV settings
    config.include('pyramid_tablib')

    # mako settings
    def add_renderer_globals(event):
        def _has_permission(name):
            return has_permission(name, RootFactory, event["request"])

        def static_ver(full, name):
            if full:
                url = event["request"].static_url('votabo:static/' + name)
            else:
                url = event["request"].static_path('votabo:static/' + name)

            fpath = os.path.join(os.path.dirname(__file__), "static", name)
            if os.path.exists(fpath):
                url = url + "?ts=" + str(int(os.stat(fpath).st_mtime))

            return url

        event['has_permission'] = lambda perm: True
        event['static_url'] = lambda name: static_ver(True, name)
        event['static_path'] = lambda name: static_ver(False, name)
        event['static_link'] = lambda name: static_ver(False, name)
        event['route_url'] = event["request"].route_url
        event['route_path'] = event["request"].route_path
        event['route_link'] = event["request"].route_path
        event['has_permission'] = _has_permission
    config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')
예제 #58
0
def set_json_renderer(config):
    """
        Customize json renderer to allow datetime rendering
    """
    json_renderer = JSON()
    def toisoformat(obj, request):
        return obj.isoformat()
    json_renderer.add_adapter(datetime.datetime, toisoformat)
    json_renderer.add_adapter(datetime.date, toisoformat)
    json_renderer.add_adapter(colander._null, lambda _, r:"null")

    def decimal_to_num(obj, request):
        return float(obj)

    json_renderer.add_adapter(Decimal, decimal_to_num)

    config.add_renderer('json', json_renderer)
    return config
예제 #59
0
def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.include('cornice')
    config.scan('monolith.web.views')
    config.add_static_view(name='media', path='monolith.web:media')
    json_renderer = JSON()

    def datetime_adapter(obj, request):
        return obj.isoformat()

    def date_adapter(obj, request):
        return '%sT00:00:00' % obj.isoformat()

    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(datetime.date, date_adapter)
    config.add_renderer('json', json_renderer)
    settings = config.registry.settings

    host = settings.get('elasticsearch.host', 'http://localhost:9200')
    prefix = settings.get('elasticsearch.prefix', '')

    logger.info('Config is set to query %s/%stime_*' % (host, prefix))

    statsd_settings = {
        'host': settings.get('statsd.host', 'localhost'),
        'port': int(settings.get('statsd.port', 8125)),
        'prefix': settings.get('statsd.prefix', ''),
    }
    config.registry.statsd = StatsClient(**statsd_settings)

    # XXX we need a way to lazy-inject this to the cornice views
    cors_origins = settings.get('cors.origins', '*')
    cors_origins = cors_origins.split(',')

    config.registry.es = ElasticSearch(host)
    config.registry.prefix = prefix
    config.add_subscriber(attach_request, NewRequest)

    return config.make_wsgi_app()