Exemplo n.º 1
0
def add_redirect(config: pyramid.config.Configurator, name: str, from_: str,
                 to: str) -> None:
    def redirect_view(request: pyramid.request.Request) -> HTTPFound:
        return HTTPFound(location=request.route_url(to))

    config.add_route(name, from_, request_method="GET")
    config.add_view(redirect_view, route_name=name)
Exemplo n.º 2
0
def add_interface_ngeo(
    config: pyramid.config.Configurator,
    route_name: str,
    route: str,
    renderer: Optional[str] = None,
    permission: Optional[str] = None,
) -> None:
    """Add the ngeo interfaces views and routes."""

    config.add_route(route_name, route, request_method="GET")
    # Permalink theme: recover the theme for generating custom viewer.js url
    config.add_route(
        f"{route_name}theme",
        f"{route}{'' if route[-1] == '/' else '/'}theme/{{themes}}",
        request_method="GET",
    )
    config.add_view(Entry,
                    attr="get_ngeo_index_vars",
                    route_name=route_name,
                    renderer=renderer,
                    permission=permission)
    config.add_view(
        Entry,
        attr="get_ngeo_index_vars",
        route_name=f"{route_name}theme",
        renderer=renderer,
        permission=permission,
    )
Exemplo n.º 3
0
def add_interface_canvas(
    config: pyramid.config.Configurator,
    route_name: str,
    route: str,
    interface_config: Dict[str, Any],
    permission: Optional[str] = None,
) -> None:
    """Add the ngeo interfaces views and routes."""

    renderer = f"/etc/geomapfish/interfaces/{route_name}.html.mako"
    config.add_route(route_name, route, request_method="GET")
    # Permalink theme: recover the theme for generating custom viewer.js URL
    config.add_route(
        f"{route_name}theme",
        f"{route}{'' if route[-1] == '/' else '/'}theme/{{themes}}",
        request_method="GET",
    )
    view = partial(canvas_view, interface_config=interface_config)
    view.__module__ = canvas_view.__module__
    config.add_view(
        view,
        route_name=route_name,
        renderer=renderer,
        permission=permission,
    )
    config.add_view(
        view,
        route_name=f"{route_name}theme",
        renderer=renderer,
        permission=permission,
    )
Exemplo n.º 4
0
def init(config: pyramid.config.Configurator) -> None:
    base_path = _utils.get_base_path(config)
    if base_path != '':
        config.add_route("c2c_index", base_path, request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index", http_cache=0)
        config.add_route("c2c_index_slash", base_path + "/", request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index_slash", http_cache=0)
Exemplo n.º 5
0
def init(config: pyramid.config.Configurator) -> None:
    if os.path.isfile(VERSIONS_PATH):
        versions = _read_versions()
        config.add_route("c2c_versions",
                         _utils.get_base_path(config) + r"/versions.json",
                         request_method="GET")
        config.add_view(lambda request: versions,
                        route_name="c2c_versions",
                        renderer="fast_json",
                        http_cache=0)
        LOG.info("Installed the /versions.json service")
        git_hash = versions['main']['git_hash']

        if 'git_tag' in versions['main']:
            LOG.warning("Starting version %s (%s)",
                        versions['main']['git_tag'], git_hash)
        else:
            LOG.warning("Starting version %s", git_hash)

        if stats.USE_TAGS:
            stats.increment_counter(['version'],
                                    1,
                                    tags=dict(version=git_hash))
        else:
            stats.increment_counter(['version', git_hash], 1)
Exemplo n.º 6
0
def add_interface_ngeo(
    config: pyramid.config.Configurator,
    route_name: str,
    route: str,
    renderer: str = None,
    permission: str = None,
) -> None:

    config.add_route(route_name, route, request_method="GET")
    config.add_view(Entry,
                    attr="get_ngeo_index_vars",
                    route_name=route_name,
                    renderer=renderer,
                    permission=permission)
    # Permalink theme: recover the theme for generating custom viewer.js url
    config.add_route(
        "{}theme".format(route_name),
        "{}{}theme/{{themes}}".format(route, "" if route[-1] == "/" else "/"),
        request_method="GET",
    )
    config.add_view(
        Entry,
        attr="get_ngeo_index_vars",
        route_name="{}theme".format(route_name),
        renderer=renderer,
        permission=permission,
    )
Exemplo n.º 7
0
def _add_view(config: pyramid.config.Configurator, name: str, path: str,
              view: Callable[[pyramid.request.Request], Any]) -> None:
    config.add_route("c2c_debug_" + name,
                     config_utils.get_base_path(config) + r"/debug/" + path,
                     request_method="GET")
    config.add_view(view,
                    route_name="c2c_debug_" + name,
                    renderer="fast_json",
                    http_cache=0)
Exemplo n.º 8
0
def init(config: pyramid.config.Configurator) -> None:
    config.add_route("c2c_read_stats_json",
                     _utils.get_base_path(config) + r"/stats.json",
                     request_method="GET")
    memory_backend = cast(stats.MemoryBackend, stats.BACKENDS['memory'])
    config.add_view(memory_backend.get_stats,
                    route_name="c2c_read_stats_json",
                    renderer="fast_json",
                    http_cache=0)
Exemplo n.º 9
0
def add_cors_route(config: pyramid.config.Configurator, pattern: str,
                   service: str) -> None:
    """Add the OPTIONS route and view need for services supporting CORS."""
    def view(request: pyramid.request.Request) -> pyramid.response.Response:
        return set_common_headers(request, service, Cache.PRIVATE_NO)

    name = pattern + "_options"
    config.add_route(name, pattern, request_method="OPTIONS")
    config.add_view(view, route_name=name)
Exemplo n.º 10
0
def _static(config: pyramid.config.Configurator):
    config.add_route(name='index', path='/*subpath')
    config.add_view(
        request_method='GET',
        route_name='index',
        view=pyramid.static.static_view(
            root_dir='megadloader:static/',
            package_name='megadloader:static',
        ),
    )
Exemplo n.º 11
0
def _make_application(*, geoip, socket):
    """Construct a Pyramid WSGI application.

    This creates a central Pyramid configurator then adds all routes, views
    and Jinja2 configuration to it.

    :mod:`pyramid_jinja2` is included into the configuration. The search path
    for Jinja2 is set to the ``templates/`` directory. The Jinja2 syntax is
    modified so that it uses square brackets instead of curly ones. E.g.
    ``{{foo}}`` becomes ``[[foo]]``. This applies to Jinja2 statements as
    well as comments.

    A route and view is added for ``/`` which serves the Angular application.
    A default 'not found' view is also added which also serves the Angular
    application. This is so that the Angular ``$location`` service can use
    *HTML5 mode* routing. Because of this there is no guarantee that a matched
    route will be set for the current request inside the entry point template.
    E.g. you can't use ``request.current_route_url``.

    Static views are added for the ``external``, ``scripts``, ``styles``,
    ``images``, ``templates`` and ``data`` directories. These are all served
    directly from the route. E.g. templates are served from ``/templates/``.

    The configuration for Steam OpenID authentication and the location
    service is added.

    :param pathlib.Path geoip: the path to the GeoIP database to use for
        the location service.
    :param str socket: the websocket URL the UI should connect to.

    :return: a WSGI application.
    """
    config = pyramid.config.Configurator(settings={
        "pyramid.reload_templates": True,
    })
    config.include("pyramid_jinja2")
    config.add_jinja2_search_path(__name__ + ":templates/")
    config.add_route("main", "/")
    config.add_view(route_name="main", renderer="main.jinja2")
    config.add_notfound_view(_404, renderer="main.jinja2")
    for static in ["external", "scripts",
                   "styles", "images", "templates", "data"]:
        config.add_static_view(static, "{}:{}/".format(__name__, static))
    _configure_authentication(config)
    _configure_location(config, geoip)
    config.commit()
    jinja2_env = config.get_jinja2_environment()
    jinja2_env.block_start_string = "[%"
    jinja2_env.block_end_string = "%]"
    jinja2_env.variable_start_string = "[["
    jinja2_env.variable_end_string = "]]"
    jinja2_env.comment_start_string = "[#"
    jinja2_env.comment_end_string = "#]"
    jinja2_env.globals["socket"] = socket
    return config.make_wsgi_app()
def includeme(config: pyramid.config.Configurator) -> None:
    for pattern, view, request_method in [
        ('/api/sign_in', api.sign_in, 'POST'),
        ('/api/sign_up', api.sign_up, 'POST'),
    ]:
        config.add_route(pattern, pattern, request_method=request_method)
        config.add_view(view,
                        route_name=pattern,
                        request_method=request_method)

    config.add_view(api.error, context=Exception)
Exemplo n.º 13
0
def add_admin_interface(config: pyramid.config.Configurator) -> None:
    if config.get_settings().get("enable_admin_interface", False):
        config.add_request_method(
            lambda request: c2cgeoportal_commons.models.DBSession(),
            "dbsession",
            reify=True,
        )
        config.add_view(c2cgeoportal_geoportal.views.add_ending_slash,
                        route_name="admin_add_ending_slash")
        config.add_route("admin_add_ending_slash",
                         "/admin",
                         request_method="GET")
        config.include("c2cgeoportal_admin")
Exemplo n.º 14
0
def add_getitfixed(config: pyramid.config.Configurator) -> None:
    if config.get_settings()["getitfixed"].get("enabled", False):
        for route_name, pattern in (
            ("getitfixed_add_ending_slash", "/getitfixed"),
            ("getitfixed_admin_add_ending_slash", "/getitfixed_admin"),
        ):
            config.add_view(c2cgeoportal_geoportal.views.add_ending_slash,
                            route_name=route_name)
            config.add_route(route_name, pattern, request_method="GET")
        config.include("getitfixed")
        # Register admin and getitfixed search paths together
        Form.set_zpt_renderer(c2cgeoform.default_search_paths,
                              translator=translator)
Exemplo n.º 15
0
def _configure_location(config, geoip):
    """Configure the location server.

    This adds the ``service-location`` route and corresponding view to the
    given configurator. A reified request method ``geoip`` is added which
    returns a database reader for the given GeoIP database.

    :param pathlib.Path geoip: the path to the GeoIP database to use for
        the location service.
    """
    config.add_request_method(
        lambda r: geoip2.database.Reader(str(geoip)), "geoip", reify=True)
    config.add_route("service-location", "/services/location")
    config.add_view(_location, route_name="service-location", renderer="json")
Exemplo n.º 16
0
 def test_deprecated_ranges_in_route_predicate(self):
     config = self._makeConfig()
     config.add_route('foo', '/foo', accept='text/*')
     config.add_view(lambda r: 'OK', route_name='foo', renderer='string')
     app = self._makeTestApp(config)
     res = app.get(
         '/foo',
         headers={'Accept': 'application/json; q=1.0, text/plain; q=0.9'},
         status=200,
     )
     self.assertEqual(res.content_type, 'text/plain')
     self.assertEqual(res.body, b'OK')
     res = app.get('/foo',
                   headers={'Accept': 'application/json'},
                   status=404)
     self.assertEqual(res.content_type, 'application/json')
Exemplo n.º 17
0
 def __init__(self, config: pyramid.config.Configurator) -> None:
     config.add_route("c2c_health_check",
                      _utils.get_base_path(config) + r"/health_check",
                      request_method="GET")
     config.add_view(self._view,
                     route_name="c2c_health_check",
                     renderer="fast_json",
                     http_cache=0)
     self._checks: List[Tuple[str, Callable[[pyramid.request.Request], Any],
                              int]] = []
     redis_url = _utils.env_or_config(config, broadcast.REDIS_ENV_KEY,
                                      broadcast.REDIS_CONFIG_KEY)
     if redis_url is not None:
         self.add_redis_check(redis_url, level=2)
         if version.get_version() is not None:
             self.add_version_check(level=2)
Exemplo n.º 18
0
 def on_class_load(cls, config: pyramid.config.Configurator):
     super(cls, cls).on_class_load(config)
     # config.add_route('test_payment_form', cls.route_payment_form)
     config.add_route('yandex_money_result_redirect',
                      cls.route_result_redirect)
     settings = config.registry.settings
     # ViewsPaymentTestServer.notify_url = settings.get(ViewsPaymentTestServer.__name__+'.notify_url')
     # config.add_view(
     #     ViewsPaymentTestServer,
     #     attr='view_payment_form',
     #     route_name='test_payment_form',
     #     renderer='payment_systems/test_payment_form.jinja2'
     # )
     config.add_view(ViewsPaymentClientYandexMoney,
                     attr='view_result_redirect',
                     route_name='test_payment_notify',
                     renderer='string')
Exemplo n.º 19
0
    def __init__(self, config: pyramid.config.Configurator) -> None:
        config.add_route(
            "c2c_health_check", config_utils.get_base_path(config) + r"/health_check", request_method="GET"
        )
        config.add_view(self._view, route_name="c2c_health_check", renderer="fast_json", http_cache=0)
        self._checks: List[Tuple[str, Callable[[pyramid.request.Request], Any], int]] = []

        self.name = config_utils.env_or_config(
            config,
            redis_utils.REDIS_SENTINELS_KEY,
            redis_utils.REDIS_SENTINELS_KEY_PROP,
            config_utils.env_or_config(config, redis_utils.REDIS_URL_KEY, redis_utils.REDIS_URL_KEY_PROP),
        )
        if self.name:
            self.add_redis_check(level=2)
            if version.get_version() is not None:
                self.add_version_check(level=2)
Exemplo n.º 20
0
 def on_class_load(cls, config: pyramid.config.Configurator):
     super(cls, cls).on_class_load(config)
     config.add_route('test_payment_form', cls.route_payment_form)
     config.add_route('test_payment_notify', cls.route_payment_notify)
     settings = config.registry.settings
     ViewsPaymentTestServer.notify_url = settings.get(ViewsPaymentTestServer.__name__+'.notify_url')
     config.add_view(
         ViewsPaymentTestServer,
         attr='view_payment_form',
         route_name='test_payment_form',
         renderer='payment_systems/test_payment_form.jinja2'
     )
     config.add_view(
         ViewsPaymentTestClient,
         attr='view_payment_client_notify',
         route_name='test_payment_notify',
         renderer='string'
     )
Exemplo n.º 21
0
def includeme(config: pyramid.config.Configurator) -> None:
    """Initialize the index page."""
    base_path = config_utils.get_base_path(config)
    if base_path != "":
        config.add_route("c2c_index",
                         base_path,
                         request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index", http_cache=0)
        config.add_route("c2c_index_slash",
                         base_path + "/",
                         request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index_slash", http_cache=0)

        settings = config.get_settings()
        auth_type_ = auth_type(settings)
        if auth_type_ == AuthenticationType.SECRET:
            LOG.warning(
                "It is recommended to use OAuth2 with GitHub login instead of the `C2C_SECRET` because it "
                "protects from brute force attacks and the access grant is personal and can be revoked."
            )

        if auth_type_ == AuthenticationType.GITHUB:
            config.add_route("c2c_github_login",
                             base_path + "/github-login",
                             request_method=("GET", ))
            config.add_view(_github_login,
                            route_name="c2c_github_login",
                            http_cache=0)
            config.add_route("c2c_github_callback",
                             base_path + "/github-callback",
                             request_method=("GET", ))
            config.add_view(_github_login_callback,
                            route_name="c2c_github_callback",
                            http_cache=0,
                            renderer="fast_json")
            config.add_route("c2c_github_logout",
                             base_path + "/github-logout",
                             request_method=("GET", ))
            config.add_view(_github_logout,
                            route_name="c2c_github_logout",
                            http_cache=0)
Exemplo n.º 22
0
def main(global_config, **settings):
    config = pyramid.config.Configurator(settings=settings)
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('home', '/')
    config.add_route('away_mode', '/away_mode')
    config.add_route('status', '/status')
    config.scan()
    app = config.make_wsgi_app()
    return app
Exemplo n.º 23
0
def init_wsgi_app() -> pyramid.router.Router:
    config = pyramid.config.Configurator(
        settings={
            'pyramid.includes': [
                'pyramid_jinja2',
                'pyramid_tm',
            ],
            'pyramid.reload_templates': True,
        })
    init_json_renderer(config)

    for name, path, method in [
        ('index', "/", 'GET'),
        ('api_create_step', "/api/steps", 'POST'),
        ('api_get_step', "/api/steps/{step_id:\d+}", 'GET'),
        ('api_update_step', "/api/steps/{step_id:\d+}", 'PUT'),
    ]:
        config.add_route(name, path, request_method=method)
    config.scan()

    config.add_static_view('static', '../static', cache_max_age=1)
    config.commit()

    return config.make_wsgi_app()
Exemplo n.º 24
0
def _configure_authentication(config):
    """Configure authentication policies, routes and view.

    This adds a authentication and authorisation policy to the given
    configurator. In addition to this it adds a reified request method
    called ``openid_consumer`` -- see :func:`_get_openid_consumer`.

    For authentication two routes are added: ``authenticate-begin`` and
    ``authentication-complete``. These routes are bound to the views
    :func:`_begin_authentication` and :func:`_complete_authentication`
    respectively.

    The authentication completion view will have it's renderer set to the
    ``authentication-complete.jinja2`` Jinja template.

    Authentication it self is done through Steam's OpenID provision. The
    two views added by this function implement the OpenID flow.

    An additional route ``service-profile`` and corresponding view is added
    that returns a JSON object that identifies the current user.
    """
    # TODO: DO NOT use this factory in production!
    config.set_session_factory(
        pyramid.session.SignedCookieSessionFactory("coffeedenshul"))
    authn_policy = pyramid.authentication.AuthTktAuthenticationPolicy(
        "coffeedenshul",
        hashalg="sha512",
    )
    authz_policy = pyramid.authorization.ACLAuthorizationPolicy()
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.add_request_method(
        _get_openid_consumer,
        "openid_consumer",
        reify=True,
    )
    config.add_route("authenticate-begin", "/authenticate/begin")
    config.add_route("authenticate-complete", "/authenticate/complete")
    config.add_view(_begin_authentication, route_name="authenticate-begin")
    config.add_view(
        _complete_authentication,
        route_name="authenticate-complete",
        renderer="authentication-complete.jinja2",
    )
    config.add_route("service-profile", "/services/profile")
    config.add_view(_profile, route_name="service-profile", renderer="json")
Exemplo n.º 25
0
    def add_routes(self):
        config = self.config
        config.add_route('sentry_frontend', '/sentry_frontend')
        config.add_route('login', '/login')
        config.add_route('logout', '/logout')

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

        config.add_route('home', '/')
        config.add_route('map', '/map')
        config.add_route('infobrief_print', '/infobrief_print')
        config.add_route('calendar', '/calendar')
        config.add_route('calendar_event_add', '/calendar/add')
        config.add_route(
            'calendar_event_delete',
            '/calendar/{id}/delete',
            factory='..model.Event.context_factory'
        )
        config.add_route('map_download', '/map/download')
        config.add_route('parcel_list', '/parcels')
        config.add_route('parcel_map_upload', '/parcels/{id}/upload_map',
                         factory='..model.Parcel.context_factory')
        config.add_route('parcel_map_download_check',
                         '/parcels/{id}/check_download_map',
                         factory='..model.Parcel.context_factory')
        config.add_route('parcel_map_download', '/parcels/{id}/download_map',
                         factory='..model.Parcel.context_factory')

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

        config.add_route('mail_add', '/mail/add')
        config.add_route('mail_list_inbox', '/mail/inbox')
        config.add_route('mail_list_sent', '/mail/sent')
        config.add_route('mail_list_drafts', '/mail/drafts')
        config.add_route('mail_edit', '/mail/{id}/edit',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_reply', '/mail/{id}/reply',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_status', '/mail/{id}/status',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_preview', '/mail/{id}/preview',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_print', '/mail/{id}/download',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_send', '/mail/{id}/send',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_duplicate', '/mail/{id}/duplicate',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_delete', '/mail/{id}/delete',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_list_attachments', '/mail/{id}/attachments',
                         factory='..mail.Message.context_factory')
        config.add_route('mail_attachment_del', '/mail/attachment/{id}/del',
                         factory='..mail.Attachment.context_factory')
        config.add_route('mail_attachment_white_page',
                         '/mail/attachment/{id}/change_white_page',
                         factory='..mail.Attachment.context_factory')
        config.add_route('mail_attachment_download',
                         '/mail/attachment/{id}/download',
                         factory='..mail.Attachment.context_factory')
        config.add_route('mail_postmark_open_tracking_webhook',
                         '/mail/postmark_open_tracking_webhook')
        config.add_route('mail_postmark_inbound_webhook',
                         '/mail/postmark_inbound_webhook')

        config.add_route('member_assignments', '/members/assignment_attendees')
        config.add_route('member_assignments_bill',
                         '/members/assignment_attendees/bill')
        config.add_route('member_assignments_detail',
                         '/members/assignment_attendees/{id}/list',
                         factory='..model.Member.context_factory')
        config.add_route('member_add', '/members/add')
        config.add_route('member_edit',
                         '/members/{id}/edit',
                         factory='..model.Member.context_factory')
        config.add_route('member_attachment_add',
                         '/members/{id}/attachments/add',
                         factory='..model.Member.context_factory')
        config.add_route('member_attachment', '/members/{id}/attachments',
                         factory='..model.Member.context_factory')
        config.add_route(
            'member_attachment_download',
            '/members/{member_id}/attachments/{id}/download',
            factory='..model.MemberAttachment.context_factory')
        config.add_route(
            'member_attachment_delete',
            '/members/{member_id}/attachments/{id}/delete',
            factory='..model.MemberAttachment.context_factory')
        config.add_route('member_account_list', '/members/account_list')
        config.add_route('member_account_detail_list',
                         '/members/{id}/account_details',
                         factory='..model.Member.context_factory')
        config.add_route(
            'member_account_detail_switch_ir',
            '/members/{member_id}/account_details/{id}/switch',
            factory='.account.AccountDetailFactory')
        config.add_route('banking_account_list', '/accounts/list')
        config.add_route('banking_account_list_detail',
                         '/accounts/{id}/detail',
                         factory='..account.BookingKind.context_factory')
        config.add_route('banking_account_list_report', '/accounts/report.pdf')
        config.add_route('sepa_sammler_list', '/accounts/sepa_sammler')
        config.add_route('sepa_sammler_add', '/accounts/sepa_sammler/add')
        config.add_route(
            'sepa_ueberweisung_add',
            '/accounts/sepa_sammler/add_ueberweisung'
        )
        config.add_route('sepa_sammler_edit',
                         '/accounts/sepa_sammler/{id}/edit',
                         factory='..account.SEPASammler.context_factory')
        config.add_route('sepa_sammler_export',
                         '/accounts/sepa_sammler/{id}/export',
                         factory='..account.SEPASammler.context_factory')
        config.add_route('sepa_sammler_update',
                         '/accounts/sepa_sammler/{id}/update',
                         factory='..account.SEPASammler.context_factory')
        config.add_route('sepa_sammler_entry_list',
                         '/accounts/sepa_sammler/{id}/entries',
                         factory='..account.SEPASammler.context_factory')
        config.add_route('sepa_direct_debit', '/accounts/sepa_direct_debit')
        config.add_route('booking_list', '/accounts/{id}/list',
                         factory='..account.BankingAccount.context_factory')
        config.add_route('split_booking', '/booking/{id}/split',
                         factory='..account.Booking.context_factory')
        config.add_route('map_booking', '/booking/{id}/map',
                         factory='..account.Booking.context_factory')

        config.add_route('waste_water', '/waste_water')
        config.add_route('property_tax_b', '/property_tax_b')

        config.add_route('member_list', '/members')
        config.add_route('member_list_leased', '/members_leased')
        config.add_route('member_list_passive', '/members_passive')
        config.add_route('member_list_tap_water', '/members_tap_water')
        config.add_route('member_sale_history', '/members/sale_history')
        config.add_route('membership_fee', '/members/insert_membership_fee')
        config.add_route('member_sale',
                         '/members/{id}/sale',
                         factory='..model.Member.context_factory')
        config.add_route('direct_debit_letter',
                         '/members/{id}/direct_debit_letter',
                         factory='..model.Member.context_factory')
        config.add_route('become_member_letter',
                         '/members/{id}/become_member_letter',
                         factory='..model.Member.context_factory')
        config.add_route('mv_entrance_list', '/members/mv_entrance_list')

        config.add_route('energy_meter_export', '/electricity/export')
        config.add_route('energy_meter_import', '/electricity/import')
        config.add_route('calculate_energy_values',
                         '/electricity/calculate_energy_values')

        config.add_route('access_authority', '/access_authority')
        config.add_route('access_authority_detail',
                         '/access_authority/{id}/list',
                         factory='.authority.AuthorityContext.context_factory')
        config.add_route('access_authority_detail_add',
                         '/access_authority/{id}/list/add',
                         factory='.authority.AuthorityContext.context_factory')
        config.add_route(
            'access_authority_detail_edit',
            '/access_authority/{viewname}/list/{id}/edit',
            factory='..model.AccessAuthority.context_factory')
        config.add_route(
            'access_authority_detail_delete',
            '/access_authority/{viewname}/list/{id}/delete',
            factory='..model.AccessAuthority.context_factory')

        config.add_route('energy_price', '/energy_price')
        config.add_route('electricity_list', '/electricity')
        config.add_route('global_energy_value_list', '/electricity_billing')
        config.add_route('energy_value_list',
                         '/electricity/{id}/history',
                         factory='..electricity.ElectricMeter.context_factory')
        config.add_route('advance_pay_value_list',
                         '/electricity/{id}/advance_pay_history',
                         factory='..electricity.ElectricMeter.context_factory')

        config.add_route('externals', '/externals')
        config.add_route('external_add', '/externals/add')
        config.add_route('external_edit', '/externals/{id}/edit',
                         factory='..mail.ExternalRecipient.context_factory')
        config.add_route('external_delete', '/externals/{id}/delete',
                         factory='..mail.ExternalRecipient.context_factory')

        config.add_route('bulletins', '/bulletins')
        config.add_route('bulletin_add', '/bulletins/add')
        config.add_route('bulletin_edit', '/bulletins/{id}/edit',
                         factory='..bulletins.Bulletin.context_factory')
        config.add_route('bulletin_delete', '/bulletins/{id}/delete',
                         factory='..bulletins.Bulletin.context_factory')
        config.add_route('bulletin_print', '/bulletins/{id}/print',
                         factory='..bulletins.Bulletin.context_factory')

        config.add_route('keylists', '/keylists')
        config.add_route('keylist_add', '/keylists/add')
        config.add_route('keylist_edit', '/keylists/{id}/edit',
                         factory='..keylist.Keylist.context_factory')
        config.add_route('keylist_delete', '/keylists/{id}/delete',
                         factory='..keylist.Keylist.context_factory')
        config.add_route('keys', '/keylists/{id}/keys',
                         factory='..keylist.Keylist.context_factory')
        config.add_route('key_add', '/keylists/{id}/keys/add',
                         factory='..keylist.Keylist.context_factory')
        config.add_route(
            'key_edit',
            '/keylists/{keylist_id}/keys/{id}/edit',
            factory='..keylist.Key.context_factory')
        config.add_route(
            'key_delete',
            '/keylists/{keylist_id}/keys/{id}/delete',
            factory='..keylist.Key.context_factory')
        config.add_route('keylist_attachment_add',
                         '/keylists/{id}/attachments/add',
                         factory='..keylist.Keylist.context_factory')
        config.add_route('keylist_attachment', '/keylists/{id}/attachments',
                         factory='..keylist.Keylist.context_factory')
        config.add_route(
            'keylist_attachment_download',
            '/keylists/{keylist_id}/attachments/{id}/download',
            factory='..keylist.KeylistAttachment.context_factory')

        config.add_route('protocols', '/protocols')
        config.add_route('protocol_add', '/protocols/add')
        config.add_route('protocol_edit', '/protocols/{id}/edit',
                         factory='..protocol.Protocol.context_factory')
        config.add_route('protocol_delete', '/protocols/{id}/delete',
                         factory='..protocol.Protocol.context_factory')
        config.add_route('protocol_detail', '/protocols/{id}/details',
                         factory='..protocol.Protocol.context_factory')
        config.add_route('protocol_detail_add', '/protocols/{id}/details/add',
                         factory='..protocol.Protocol.context_factory')
        config.add_route(
            'protocol_detail_edit',
            '/protocols/{protocol_id}/details/{id}/edit',
            factory='..protocol.ProtocolDetail.context_factory')
        config.add_route(
            'protocol_detail_delete',
            '/protocols/{protocol_id}/details/{id}/delete',
            factory='..protocol.ProtocolDetail.context_factory')
        config.add_route('protocol_print', '/protocols/{id}/print',
                         factory='..protocol.Protocol.context_factory')
        config.add_route('protocol_attachment_add',
                         '/protocols/{id}/attachments/add',
                         factory='..protocol.Protocol.context_factory')
        config.add_route('protocol_attachment', '/protocols/{id}/attachments',
                         factory='..protocol.Protocol.context_factory')
        config.add_route(
            'protocol_attachment_download',
            '/protocols/{protocol_id}/attachments/{id}/download',
            factory='..protocol.ProtocolAttachment.context_factory')
        config.add_route(
            'protocol_attachment_delete',
            '/protocols/{protocol_id}/attachments/{id}/delete',
            factory='..protocol.ProtocolAttachment.context_factory')
        config.add_route('protocol_commitment', '/protocols/{id}/commitments',
                         factory='..protocol.Protocol.context_factory')
        config.add_route('protocol_commitment_add',
                         '/protocols/{id}/commitments/add',
                         factory='..protocol.Protocol.context_factory')
        config.add_route(
            'protocol_commitment_edit',
            '/protocols/{protocol_id}/commitments/{id}/edit',
            factory='..protocol.ProtocolCommitment.context_factory')
        config.add_route(
            'protocol_commitment_delete',
            '/protocols/{protocol_id}/commitments/{id}/delete',
            factory='..protocol.ProtocolCommitment.context_factory')

        config.add_route('assignments', '/assignments')
        config.add_route('assignment_add', '/assignments/add')
        config.add_route('assignment_edit', '/assignments/{id}/edit',
                         factory='..assignment.Assignment.context_factory')
        config.add_route('assignment_delete', '/assignments/{id}/delete',
                         factory='..assignment.Assignment.context_factory')
        config.add_route('assignment_list_attendees', '/assignments/{id}/list',
                         factory='..assignment.Assignment.context_factory')
        config.add_route('assignment_attendees_add',
                         '/assignments/{id}/attendees/add',
                         factory='..assignment.Assignment.context_factory')
        config.add_route(
            'assignment_attendees_edit',
            '/assignments/{assignment_id}/attendees/{id}/edit',
            factory='..assignment.AssignmentAttendee.context_factory')

        config.add_route(
            'assignment_attendees_delete',
            '/assignments/{assignment_id}/attendees/{id}/delete',
            factory='..assignment.AssignmentAttendee.context_factory')

        config.add_route('depots', '/depots')
        config.add_route('depot_add', '/depots/add')
        config.add_route('depot_edit', '/depots/{id}/edit',
                         factory='..depot.Depot.context_factory')
        config.add_route('depot_delete', '/depots/{id}/delete',
                         factory='..depot.Depot.context_factory')
        config.add_route('depot_download', '/depots/{id}/download',
                         factory='..depot.Depot.context_factory')
Exemplo n.º 26
0
def add_routes(config):
    config.add_route('stripe', '/stripe')
Exemplo n.º 27
0
import pyramid.config
import pyramid.response

from config import PING_MESSAGE


# noinspection PyUnusedLocal
def ping(request):
    return pyramid.response.Response(PING_MESSAGE.format(app='pyramid'))


with pyramid.config.Configurator() as config:
    config.add_route('ping', '/')
    config.add_view(ping, route_name='ping')
    app = config.make_wsgi_app()
Exemplo n.º 28
0
def _api(config: pyramid.config.Configurator):
    config.add_route('api: status', '/api/status')
    config.add_view(
        request_method='GET',
        route_name='api: status',
        view=handle_status,
        renderer='json',
    )

    config.add_route('api: categories', '/api/categories/')
    config.add_view(
        request_method='GET',
        route_name='api: categories',
        view=handle_list_categories,
        renderer='json',
    )
    config.add_view(
        request_method='POST',
        route_name='api: categories',
        view=handle_create_category,
        renderer='json',
    )

    config.add_route('api: urls', '/api/urls/')
    config.add_view(
        request_method='GET',
        route_name='api: urls',
        view=handle_get_urls,
        renderer='json',
    )
    config.add_view(
        request_method='POST',
        route_name='api: urls',
        view=handle_add_url,
        renderer='json',
    )

    config.add_route('api: queue items', '/api/queue/{queue_id}')
    config.add_view(
        request_method='DELETE',
        route_name='api: queue items',
        view=handle_delete_url,
        renderer='json',
    )

    config.add_route('api: files', '/api/files/')
    config.add_view(
        request_method='GET',
        route_name='api: files',
        view=handle_list_files,
        renderer='json',
    )

    config.add_route('api: file', '/api/files/{file_id}')
    config.add_view(
        request_method='GET',
        route_name='api: file',
        view=handle_get_file,
        renderer='json',
    )
Exemplo n.º 29
0
 def add_static_route(name: str, attr: str, path: str,
                      renderer: str) -> None:
     config.add_route(name, path, request_method="GET")
     config.add_view(Entry, attr=attr, route_name=name, renderer=renderer)
Exemplo n.º 30
0
from supergroup import SuperGroup

#Use pymongo
from pymongo import MongoClient
from mongokit import Document, Connection

from bson import json_util
from pyramid.renderers import JSON

if __name__ == '__main__':
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config = Configurator(session_factory = my_session_factory)
    config.include('pyramid_debugtoolbar')
    config.add_settings({'mako.directories':'templates/'})
    config.add_static_view(name='static', path='static')
    config.add_route('home', '/')
    config.add_route('about', '/about')
    config.add_view(home, route_name='home')
    mgconnection = MongoClient()
    db = mgconnection.test

    # Clear database
    db.drop_collection('users')
    db.drop_collection('groups')

    connection = Connection()
    connection.register([User,Group,SuperGroup])

    group = connection.Group()
    group["name"] = "sampleGroup"
    group["creation_date"] = datetime.utcnow()
Exemplo n.º 31
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    model.setup()

    session_factory = session_factory_from_settings(settings)
    
    config = Configurator(
        settings=settings,
        root_factory=security.RootFactory,
        authentication_policy=AuthTktAuthenticationPolicy(
            settings["cookie_secret"],
            callback=security.group_finder),
        authorization_policy=ACLAuthorizationPolicy())

    config.set_request_factory(security.RequestWithUserAttribute)
    config.set_session_factory(session_factory)
    config.add_static_view("static", "scrobble:static")
    config.add_route("home", "/",
                     view="scrobble.views.list_users",
                     view_renderer="list_users.mako")
    config.add_route("new_account", "/new_account",
                     view="scrobble.login.new_account",
                     view_renderer="new_account.mako")
    config.add_route("login", "/login",
                     view="scrobble.login.login")
    config.add_route("logout", "/logout",
                     view="scrobble.login.logout",
                     view_renderer="logout.mako")
    config.add_route("list_users", "/users",
                     view="scrobble.views.list_users",
                     view_renderer="list_users.mako")
    config.add_route("user_home", "/user/{user}",
                     view="scrobble.views.user_home",
                     view_renderer="user_home.mako")

    
    config.add_route("simulate_listen", "/simulate_listen",
                     view="scrobble.views.simulate_listen",
                     view_renderer="simulate.mako")

    config.add_route("api_login", "api/login")
    config.add_route("api_whoami", "api/whoami")
    config.add_route("api_track_listen", "api/track_listen")
    config.add_route("api_follow_user", "api/follow_user")
    config.add_route("api_unfollow_user", "api/unfollow_user")
    config.scan()
    return config.make_wsgi_app()
Exemplo n.º 32
0
def main(global_config, **settings):
    """
        This function returns a Pyramid WSGI application.
    """
    # Setup --------------------------------------------------------------------

    # Db
    init_DBSession(settings)

    # Pyramid Global Settings
    config = pyramid.config.Configurator(
        settings=settings,
        root_factory=TraversalGlobalRootFactory)  # , autocommit=True

    def assert_settings_keys(keys):
        for settings_key in key:
            assert config.registry.settings.get(settings_key)

    # Register Additional Includes ---------------------------------------------
    config.include(
        'pyramid_mako'
    )  # The mako.directories value is updated in the scan for addons. We trigger the import here to include the correct folders.

    # Reload on template change - Dedicated from pserve
    #template_filenames = map(operator.attrgetter('absolute'), file_scan(config.registry.settings['mako.directories']))
    #from pyramid.scripts.pserve import add_file_callback
    #add_file_callback(lambda: template_filenames)

    # Parse/Convert setting keys that have specified datatypes
    # Environment variables; capitalized and separated by underscores can override a settings key.
    # e.g.
    #   export KARAKARA_TEMPLATE_TITLE=Test
    #   can override 'karakara.template.title'
    for key in config.registry.settings.keys():
        value = os.getenv(
            key.replace('.', '_').upper(), ''
        ) if config.registry.settings['karakara.server.mode'] != 'test' else ''
        value = value or config.registry.settings[key]
        config.registry.settings[key] = convert_str_with_type(value)

    # Session identity
    config.add_request_method(partial(
        session_identity, session_keys={'id', 'admin', 'faves', 'user'}),
                              'session_identity',
                              reify=True)

    # Setup Cache Manager config in view
    setup_pyramid_cache_manager(config)
    # Setup Autoformat view processor
    setup_pyramid_autoformater(config)

    @post_view_dict_augmentation.register_pre_render_decorator()
    def add_paths_to_response_dict(request, response):
        response['paths'] = {
            'context': pyramid.traversal.resource_path(request.context),
            'queue': '',
        }
        try:
            queue_context = request.context.queue_context
            if queue_context:
                response['paths'].update(
                    template_helpers.paths_for_queue(queue_context.id))
        except AttributeError:
            pass

    # i18n
    config.add_translation_dirs(
        config.registry.settings['i18n.translation_dirs'])

    # Session Manager
    session_settings = extract_subkeys(config.registry.settings, 'session.')
    session_factory = SignedCookieSessionFactory(serializer=json_serializer,
                                                 **session_settings)
    config.set_session_factory(session_factory)

    from .model.actions import last_track_db_update

    def _last_track_db_update(request):
        return last_track_db_update()

    # Track DB Version ---------------------------------------------------------
    config.add_request_method(_last_track_db_update,
                              'last_track_db_update',
                              property=True,
                              reify=True)

    # Cachebust etags ----------------------------------------------------------
    #  crude implementation; count the number of tags in db, if thats changed, the etags will invalidate
    if not config.registry.settings['server.etag.cache_buster']:
        config.registry.settings[
            'server.etag.cache_buster'] = 'last_update:{0}'.format(
                str(last_track_db_update()))
        # TODO: Where is this used? How is this related to karakara.tracks.version?

    # Global State -------------------------------------------------------------
    config.registry.settings['karakara.tracks.version'] = random.randint(
        0, 20000000)

    # Search Config ------------------------------------------------------------
    import karakara.views.queue_search
    karakara.views.queue_search.search_config = read_json(
        config.registry.settings['karakara.search.view.config'])
    assert karakara.views.queue_search.search_config, 'search_config data required'

    # LogEvent -----------------------------------------------------------------

    log_event_logger = logging.getLogger('json_log_event')

    def log_event(request, **data):
        """
        It is expected that python's logging framework is used to output these
        events to the correct destination.
        Logstash can then read/process this log output for overview/stats
        """
        event = data.get('event')
        try:
            event = request.matched_route.name
        except Exception:
            pass
        try:
            event = request.context.__name__
        except Exception:
            pass
        data.update({
            'event': event,
            'session_id': request.session.get('id'),
            'ip': request.environ.get('REMOTE_ADDR'),
            'timestamp': now(),
        })
        log_event_logger.info(json_string(data))

    config.add_request_method(log_event)

    # WebSocket ----------------------------------------------------------------

    class NullAuthEchoServerManager(object):
        def recv(self, *args, **kwargs):
            pass

    socket_manager = NullAuthEchoServerManager()

    if config.registry.settings.get('karakara.websocket.port'):

        def authenticator(key):
            """Only admin authenticated keys can connect to the websocket"""
            cookie_name = config.registry.settings['session.cookie_name']
            if cookie_name in key:
                cookie = key
            else:
                cookie = '{0}={1}'.format(cookie_name, key)
            request = pyramid.request.Request({'HTTP_COOKIE': cookie})
            session_data = session_factory(request)
            return session_data and session_data.get('admin')

        def _int_or_none(setting_key):
            return int(config.registry.settings.get(setting_key)
                       ) if config.registry.settings.get(setting_key) else None

        try:
            _socket_manager = AuthEchoServerManager(
                authenticator=authenticator,
                websocket_port=_int_or_none('karakara.websocket.port'),
                tcp_port=_int_or_none('karakara.tcp.port'),
            )
            _socket_manager.start()
            socket_manager = _socket_manager
        except OSError:
            log.warn('Unable to setup websocket')

    def send_websocket_message(request, message):
        # TODO: This will have to be augmented with json and queue_id in future
        socket_manager.recv(
            message.encode('utf-8'))  # TODO: ?um? new_line needed?

    config.add_request_method(send_websocket_message)
    #config.registry['socket_manager'] = socket_manager

    # Login Providers ----------------------------------------------------------

    from .views.comunity_login import social_login
    social_login.user_store = ComunityUserStore()
    login_providers = config.registry.settings.get('login.provider.enabled')
    # Facebook
    if 'facebook' in login_providers:
        assert_settings_keys(
            ('login.facebook.appid', 'login.facebook.secret'),
            message=
            'To use facebook as a login provider appid and secret must be provided'
        )
        social_login.add_login_provider(
            FacebookLogin(
                appid=config.registry.settings.get('login.facebook.appid'),
                secret=config.registry.settings.get('login.facebook.secret'),
                permissions=config.registry.settings.get(
                    'login.facebook.permissions'),
            ))
    # Google
    if 'google' in login_providers:
        social_login.add_login_provider(
            GoogleLogin(client_secret_file=config.registry.settings.get(
                'login.google.client_secret_file'), ))
    # Firefox Persona (Deprecated technology but a useful reference)
    #if 'persona' in login_providers:
    #    social_login.add_login_provider(PersonaLogin(
    #        site_url=config.registry.settings.get('server.url')
    #    ))
    # No login provider
    if not login_providers and config.registry.settings.get(
            'karakara.server.mode') != 'test':
        # Auto login if no service keys are provided
        social_login.add_login_provider(NullLoginProvider())
        social_login.user_store = NullComunityUserStore()
    template_helpers.javascript_inline['comunity'] = social_login.html_includes

    # KaraKara request additions -----------------------------------------------

    from unittest.mock import patch

    def call_sub_view(request, view_callable, acquire_cache_bucket_func):
        """
        A wrapper for called view_callable's to allow subrequests to use correct cache_buckets
        """
        if not hasattr(request, 'cache_bucket'):
            # FFS - don't ask questions ... just ... (sigh) ... patch can ONLY patch existing attributes
            setattr(request, 'cache_bucket', 'some placeholder s***e')
        _cache_bucket = acquire_cache_bucket_func(request)
        with patch.object(request, 'cache_bucket', _cache_bucket):
            assert request.cache_bucket == _cache_bucket
            return view_callable(request)['data']

    config.add_request_method(call_sub_view)

    from .model_logic.queue_logic import QueueLogic
    config.add_request_method(QueueLogic, 'queue', reify=True)

    # Routes -------------------------------------------------------------------

    def settings_path(key):
        path = os.path.join(os.getcwd(), config.registry.settings[key])
        if not os.path.isdir(path):
            log.error('Unable to add_static_view {key}:{path}'.format(
                key=key, path=path))  #TODO: reaplce with formatstring
        return path

    # Static Routes
    config.add_static_view(
        name='ext',
        path=settings_path('static.externals'))  # cache_max_age=3600
    config.add_static_view(
        name='static',
        path=settings_path('static.assets'))  # cache_max_age=3600
    config.add_static_view(name='player', path=settings_path('static.player'))
    config.add_static_view(name='player2',
                           path=settings_path('static.player2'))

    # AllanC - it's official ... static route setup and generation is a mess in pyramid
    #config.add_static_view(name=settings["static.media" ], path="karakara:media" )
    config.add_static_view(
        name='files',
        path=config.registry.settings['static.processmedia2.config']
        ['path_processed'])

    # View Routes
    config.add_route('inject_testdata', '/inject_testdata')
    # Upload extras -----
    #config.add_static_view(name=settings['upload.route.uploaded'], path=settings['upload.path'])  # the 'upload' route above always matchs first
    config.add_route('upload', '/upload{sep:/?}{name:.*}')

    # Events -------------------------------------------------------------------
    config.add_subscriber(add_localizer_to_request, pyramid.events.NewRequest)
    config.add_subscriber(add_render_globals_to_template,
                          pyramid.events.BeforeRender)

    # Tweens -------------------------------------------------------------------
    if config.registry.settings.get(
            'karakara.server.mode'
    ) == 'development' and config.registry.settings.get(
            'karakara.server.postmortem'):
        config.add_tween('karakara.postmortem_tween_factory')

    # Return -------------------------------------------------------------------
    config.scan(ignore='.tests')
    config.scan('calaldees.pyramid_helpers.views')
    return config.make_wsgi_app()
Exemplo n.º 33
0
def _configure_routes(config):
    config.add_static_view(name='static', path='nerffinder:static')
    config.add_route('root', '/')
    config.add_view(nerffinder.views.map.map_view, route_name='root', renderer='nerffinder:templates/splash.mak')
    config.add_route('map', '/map')
    config.add_view(nerffinder.views.map.map_view, route_name='map', renderer='nerffinder:templates/map.mak')
    config.add_route('chart', '/chart')
    config.add_view(nerffinder.views.chart.chart_view, route_name='chart', renderer='nerffinder:templates/chart.mak')
    config.add_route('precache', '/precache')
    config.add_view(nerffinder.views.precache.precache_view, route_name='precache', renderer='nerffinder:templates/precache.mak')
    
    config.add_route('api_gear_categories', '/api/v1/gear/categories/')
    config.add_view(nerffinder.api.v1.gear.categories_view, route_name='api_gear_categories', renderer='json')
    config.add_route('api_gear_locations', '/api/v1/gear/locations/')
    config.add_view(nerffinder.api.v1.gear.locations_view, route_name='api_gear_locations', renderer='json')
    config.add_route('api_gear_details', '/api/v1/gear/details/{id}/')
    config.add_view(nerffinder.api.v1.gear.details_view, route_name='api_gear_details', renderer='json')