Пример #1
0
 def __init__(self, *args, **kwargs):
     super(OIDCAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('callback_uri', '/oidc/{}'.format(self.name))
     oidc_settings = self.settings.setdefault(
         'oidc', {
             'client_id': None,
             'client_secret': None,
             'authorize_url': None,
             'access_token_url': None,
             'issuer': None
         })
     oidc_settings.setdefault('logout_url', None)
     oidc_settings.setdefault('jwks_url', None)
     oidc_settings.setdefault(
         'jwks', None)  # used as a cache, but could also be pre-populated
     client_kwargs = oidc_settings.setdefault('client_kwargs', {})
     scopes = set(client_kwargs.get('scope', '').split()) | {'openid'}
     client_kwargs['scope'] = ' '.join(sorted(scopes))
     self.oauth_app = RemoteApp(
         self.name + '_flaskmultipass',
         client_id=oidc_settings['client_id'],
         client_secret=oidc_settings['client_secret'],
         authorize_url=oidc_settings['authorize_url'],
         access_token_url=oidc_settings['access_token_url'],
         client_kwargs=oidc_settings['client_kwargs'])
     self.authorized_endpoint = '_flaskmultipass_oidc_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'],
                              self.authorized_endpoint,
                              self._authorize_callback,
                              methods=('GET', 'POST'))
Пример #2
0
    def _register_commands(self, plugin):
        possible_commands = [x for x in dir(plugin) if not x.startswith('_')]
        for name in possible_commands:
            method = getattr(plugin, name)
            if callable(method) and hasattr(method, 'is_cmd'):
                commands = [method.cmd_name]
                if method.aliases is not None:
                    aliases = method.aliases
                    if isinstance(method.aliases, string_types):
                        aliases = [method.aliases]
                    for alias in aliases:
                        commands.append(alias)

                for cmd_name in commands:
                    cmd = '!' + cmd_name
                    if cmd in self.commands:
                        raise DuplicateCommandError(cmd_name)
                    self.log.info("Registered command %s",
                                  type(plugin).__name__ + '.' + cmd_name)
                    self.commands[cmd] = PluginCommand(method)
            elif callable(method) and hasattr(method, 'is_webhook'):
                self.log.info("Registered webhook %s",
                              type(plugin).__name__ + '.' + name)
                webhook = WebhookCommand(method, method.form_params)
                with plugin._bot.webserver.app.app_context():
                    current_app.add_url_rule(method.route,
                                             method.__name__,
                                             webhook.execute,
                                             methods=[method.method])
    def init_app(self, app):
        """
        Standard flask-extension initialisation

        :param app: flask app
        """

        if app is not None:
            self.app = app

        if "watchman" in app.extensions:
            raise RuntimeError("Flask application already initialised")

        app.extensions["watchman"] = self

        for view_name in self.allowed_endpoints.keys():

            if view_name not in self.kwargs.keys():
                continue

            view = self.allowed_endpoints[view_name]["view"]
            route = self.allowed_endpoints[view_name]["route"]
            methods = self.allowed_endpoints[view_name]["methods"]

            # Does the user provide scopes?
            if view_name in self.kwargs and self.kwargs[view_name].get("scopes", None) != None:
                user_config = self.kwargs[view_name]

                view.scopes = user_config.get("scopes", [])
                view.decorators = user_config.get("decorators", ([advertise("scopes", "rate_limit")]))
                view.rate_limit = [1000, 60 * 60 * 24]

            with app.app_context():
                current_app.add_url_rule(route, view_func=view.as_view(view_name), methods=methods)
Пример #4
0
def make_urls(app=None):
    if app is None:
        from flask import current_app as app

    api = Api(app)
    api.add_resource(TestResource, '/test', '/test/')

    CORS(app)
    app.config['CORS_HEADERS'] = 'Content-Type'

    # Register resources to urls
    base_version = app.config['BASE_VERSION']

    def register(resource, url):
        url = url.strip('/')
        api.add_resource(resource, '/%s/%s' % (base_version, url),
                         '/%s/%s/' % (base_version, url))

    register(ProjetoDetail, 'projetos/<string:PRONAC>/')
    register(ProjetoList, 'projetos/')
    register(ProponenteList, 'proponentes/')
    register(ProponenteDetail, 'proponentes/<string:proponente_id>/')
    register(Captacao, 'projetos/<string:PRONAC>/captacoes/')
    register(Area, 'projetos/areas')
    register(Segmento, 'projetos/segmentos/')
    register(PreProjetoList, 'propostas/')
    register(PreProjetoDetail, 'propostas/<string:id>/')
    register(IncentivadorList, 'incentivadores/')
    register(IncentivadorDetail, 'incentivadores/<string:incentivador_id>/')
    register(DoacaoList, 'incentivadores/<string:incentivador_id>/doacoes/')
    register(FornecedorList, 'fornecedores/')
    register(FornecedorDetail, 'fornecedores/<string:fornecedor_id>/')
    register(Produto, 'fornecedores/<string:fornecedor_id>/produtos/')

    app.add_url_rule('/graphql',
                     view_func=GraphQLView.as_view(
                         'graphql',
                         schema=schema,
                     ))

    app.add_url_rule('/graphiql',
                     view_func=GraphQLView.as_view('graphiql',
                                                   schema=schema,
                                                   graphiql=True))

    @app.route('/')
    def index():
        return redirect("/doc/", code=302)

    @app.route('/v1/swagger-def/')
    def swagger_def():
        return send_from_directory(BASE_PATH, SWAGGER_DEF)

    @app.route('/doc/')
    def documentation():
        return send_from_directory(STATIC_URL_PATH, 'index.html')

    @app.route('/doc/<path:path>')
    def documentation_data(path):
        return send_from_directory(STATIC_URL_PATH, path)
Пример #5
0
def _register_components(flask_app):
    # Postgres DB
    from data_engineering.common.db.models import sql_alchemy
    from data_engineering.common.db.dbi import DBI

    sql_alchemy.session = sql_alchemy.create_scoped_session()
    sql_alchemy.init_app(flask_app)
    flask_app.db = sql_alchemy
    flask_app.dbi = DBI(sql_alchemy)

    # Routes
    try:
        from app.api import routes
    except ImportError:
        pass
    else:
        for rule, view_func in routes.RULES:
            flask_app.add_url_rule(rule, view_func=view_func)

    # Healthcheck
    flask_app.add_url_rule('/healthcheck/', view_func=healthcheck),

    # Cache
    redis_uri = _get_redis_url(flask_app)
    flask_app.cache = redis.from_url(redis_uri)

    try:
        from app.application import register_app_components
    except ImportError:
        pass
    else:
        flask_app = register_app_components(flask_app)
    return flask_app
Пример #6
0
def add_resource(app, resource, pk='pk'):
    uri, endpoint, view_func = get_args(resource)

    app.add_url_rule(normalize_uri(uri), view_func=view_func,
                     methods=['OPTIONS', 'GET', 'POST', 'DELETE'])
    app.add_url_rule(normalize_uri('%s/<%s>' % (uri, pk)), view_func=view_func,
                     methods=['OPTIONS', 'GET', 'PUT', 'PATCH', 'DELETE'])
Пример #7
0
def register_api_doc():
    """全局第一个请求之前,把接口文档路由添加到应用中"""
    if current_app.config.get("ENV") == "development":
        from ..doc import generate_doc
        view_functions = [(k, v)
                          for k, v in current_app.view_functions.items()
                          if k.startswith(api.name + ".")]
        api_doc_func = partial(generate_doc,
                               view_functions=view_functions,
                               common_param_list=COMMON_PARAM_LIST,
                               response_code_list=RESPONSE_CODE_LIST)
        api_doc_endpoint = api.name + "_api_doc"
        api_doc_url = api.url_prefix + "/doc/"
        current_app.add_url_rule(api_doc_url,
                                 view_func=api_doc_func,
                                 endpoint=api_doc_endpoint,
                                 methods=["GET"])
        # 由于请求分发(full_dispatch_request)之前request的内容就已经通过request_context装载完毕,那时候url_map中还没有文档接口。
        # 如果恰好第一个request就要请求文档接口,会导致request_context装载时match_request失败,产生404错误,然后调用请求分发时会弹出这个错误。
        # 这里在匹配到请求文档接口的意图后,手动修改request请求体,把错误去除后再把url_rule装载到请求体里,就可以了。
        if request.path == api_doc_url and request.method.upper() == "GET":
            request.routing_exception = None
            request.url_rule = current_app.url_map._rules_by_endpoint[
                api_doc_endpoint][0]
            request.view_args = {}
Пример #8
0
 def __init__(self, *args, **kwargs):
     super(ShibbolethAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('attrs_prefix', 'ADFS_')
     if not self.settings.get('callback_uri'):
         raise MultipassException("`callback_uri` must be specified in the provider settings")
     self.shibboleth_endpoint = '_flaskmultipass_shibboleth_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'], self.shibboleth_endpoint,
                              self._shibboleth_callback, methods=('GET', 'POST'))
Пример #9
0
 def _create_login_rule(self):
     """Creates the login URL rule if necessary"""
     endpoint = current_app.config['MULTIPASS_LOGIN_ENDPOINT']
     rules = current_app.config['MULTIPASS_LOGIN_URLS']
     if rules is None:
         return
     for rule in rules:
         current_app.add_url_rule(rule, endpoint, self.process_login, methods=('GET', 'POST'))
Пример #10
0
 def _create_login_rule(self):
     """Creates the login URL rule if necessary"""
     endpoint = current_app.config['MULTIPASS_LOGIN_ENDPOINT']
     rules = current_app.config['MULTIPASS_LOGIN_URLS']
     if rules is None:
         return
     for rule in rules:
         current_app.add_url_rule(rule, endpoint, self.process_login, methods=('GET', 'POST'))
Пример #11
0
 def __init__(self, *args, **kwargs):
     super(ShibbolethAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('attrs_prefix', 'ADFS_')
     if not self.settings.get('callback_uri'):
         raise MultipassException("`callback_uri` must be specified in the provider settings")
     self.shibboleth_endpoint = '_flaskmultipass_shibboleth_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'], self.shibboleth_endpoint,
                              self._shibboleth_callback, methods=('GET', 'POST'))
Пример #12
0
def add_route_for_snippet(mountpoint):
    """Register a route for the snippet."""
    endpoint = '{}.{}'.format(blueprint.name, mountpoint.endpoint_suffix)
    defaults = {'name': mountpoint.snippet.name}

    current_app.add_url_rule(mountpoint.url_path,
                             endpoint,
                             view_func=view_latest_by_name,
                             defaults=defaults)
Пример #13
0
 def __init__(self, *args, **kwargs):
     super(OAuthAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('callback_uri', '/oauth/{}'.format(self.name))
     self.settings.setdefault('oauth', {})
     self.settings.setdefault('token_field', 'access_token')
     self.oauth_app = OAuth.instance.remote_app(self.name + '_flaskmultipass', register=False,
                                                **self.settings['oauth'])
     self.authorized_endpoint = '_flaskmultipass_oauth_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'], self.authorized_endpoint,
                              self._authorize_callback, methods=('GET', 'POST'))
Пример #14
0
def add_route_for_snippet(mountpoint):
    """Register a route for the snippet."""
    endpoint = '{}.{}'.format(blueprint.name, mountpoint.endpoint_suffix)
    defaults = {'name': mountpoint.snippet.name}

    current_app.add_url_rule(
        mountpoint.url_path,
        endpoint,
        view_func=view_latest_by_name,
        defaults=defaults)
Пример #15
0
 def __init__(self, *args, **kwargs):
     super(OAuthAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('callback_uri', '/oauth/{}'.format(self.name))
     self.settings.setdefault('oauth', {})
     self.settings.setdefault('token_field', 'access_token')
     self.oauth_app = OAuth.instance.remote_app(self.name + '_flaskmultipass', register=False,
                                                **self.settings['oauth'])
     self.authorized_endpoint = '_flaskmultipass_oauth_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'], self.authorized_endpoint,
                              self._authorize_callback, methods=('GET', 'POST'))
Пример #16
0
def add_route_for_snippet(mountpoint):
    """Register a route for the snippet."""
    endpoint = f'{snippet_blueprint.name}.{mountpoint.endpoint_suffix}'
    defaults = {'name': mountpoint.endpoint_suffix}

    current_app.add_url_rule(
        mountpoint.url_path,
        endpoint,
        view_func=view_current_version_by_name,
        defaults=defaults,
    )
Пример #17
0
 def __init__(self, *args, **kwargs):
     super(OAuthAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('callback_uri', '/oauth/{}'.format(self.name))
     oauth_settings = self.settings.setdefault('oauth', {})
     self.oauth_app = RemoteApp(self.name + '_flaskmultipass',
                                **oauth_settings)
     self.authorized_endpoint = '_flaskmultipass_oauth_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'],
                              self.authorized_endpoint,
                              self._authorize_callback,
                              methods=('GET', 'POST'))
Пример #18
0
def register_service(cls, primary_key_type):
    """Register an API service endpoint.

    :param cls: The class to register
    :param str primary_key_type: The type (as a string) of the primary_key
                                 field
    """
    view_func = cls.as_view(cls.__name__.lower())  # pylint: disable=no-member
    methods = set(cls.__model__.__methods__)  # pylint: disable=no-member

    if 'GET' in methods:  # pylint: disable=no-member
        current_app.add_url_rule(
            cls.__model__.__url__ + '/', defaults={'resource_id': None},
            view_func=view_func,
            methods=['GET'])
        current_app.add_url_rule(
            '{resource}/meta'.format(resource=cls.__model__.__url__),
            view_func=view_func,
            methods=['GET'])
    if 'POST' in methods:  # pylint: disable=no-member
        current_app.add_url_rule(
            cls.__model__.__url__ + '/', view_func=view_func, methods=['POST', ])
    current_app.add_url_rule(
        '{resource}/<{pk_type}:{pk}>'.format(
            resource=cls.__model__.__url__,
            pk='resource_id', pk_type=primary_key_type),
        view_func=view_func,
        methods=methods - {'POST'})
    current_app.classes.append(cls)
Пример #19
0
 def __init__(self, *args, **kwargs):
     super(CASAuthProvider, self).__init__(*args, **kwargs)
     self.settings.setdefault('callback_uri',
                              '/cas_auth/{}'.format(self.name))
     if not self.settings.get('cas_url_base'):
         raise MultipassException(
             "`cas_url_base` must be specified in the provider settings")
     self.cas_client = CASClient(self.settings['cas_url_base'],
                                 auth_prefix='')
     self.cas_endpoint = '_flaskmultipass_cas_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'],
                              self.cas_endpoint,
                              self._authorize_callback,
                              methods=('GET', 'POST'))
Пример #20
0
    def register_service(cls, primary_key_type):
        """Register an API service endpoint.

        :param cls: The class to register
        :param str primary_key_type: The type (as a string) of the primary_key
                                     field
        """
        view_func = cls.as_view(cls.__name__.lower())  # pylint: disable=no-member
        methods = set(cls.__model__.__methods__)  # pylint: disable=no-member

        if 'GET' in methods:  # pylint: disable=no-member
            current_app.add_url_rule(
                cls.__model__.__url__ + '/', defaults={'resource_id': None},
                view_func=view_func,
                methods=['GET'])
            current_app.add_url_rule(
                '{resource}/meta'.format(resource=cls.__model__.__url__),
                view_func=view_func,
                methods=['GET'])
        if 'POST' in methods:  # pylint: disable=no-member
            current_app.add_url_rule(
                cls.__model__.__url__ + '/', view_func=view_func, methods=['POST', ])
        current_app.add_url_rule(
            '{resource}/<{pk_type}:{pk}>'.format(
                resource=cls.__model__.__url__,
                pk='resource_id', pk_type=primary_key_type),
            view_func=view_func,
            methods=methods - {'POST'})
        current_app.classes.append(cls)
Пример #21
0
def register_service(cls, primary_key_type="int"):
    """Register an API service endpoint.

    :param cls: The class to register
    :param str primary_key_type: The type (as a string) of the primary_key
                                 field
    """
    view_func = cls.as_view(cls.__name__.lower())  # pylint: disable=no-member
    methods = set(cls.__model__.__methods__)  # pylint: disable=no-member

    if "GET" in methods:  # pylint: disable=no-member
        current_app.add_url_rule(
            cls.__model__.__url__, defaults={"resource_id": None}, view_func=view_func, methods=["GET"]
        )
        current_app.add_url_rule(
            "{resource}/meta".format(resource=cls.__model__.__url__), view_func=view_func, methods=["GET"]
        )
    if "POST" in methods:  # pylint: disable=no-member
        current_app.add_url_rule(cls.__model__.__url__, view_func=view_func, methods=["POST"])
    current_app.add_url_rule(
        "{resource}/<{pk_type}:{pk}>".format(
            resource=cls.__model__.__url__, pk="resource_id", pk_type=primary_key_type
        ),
        view_func=view_func,
        methods=methods - set(["POST"]),
    )
Пример #22
0
def test_before_request(client, dummy_api):
    def test_route_1():
        return "OK", 200

    endpoint = "/"
    query_params = dict(a="1")
    current_app.add_url_rule(endpoint,
                             test_route_1.__name__,
                             view_func=test_route_1)
    client.get(endpoint, query_string=query_params)
    dummy_api(api_version="1.0").before_request(name=test_route_1.__name__)
    assert getattr(g, "request_start_time", None) is not None
    assert getattr(g, "request_id", None) is not None
    assert getattr(g, "api_version", None) is not None
    assert getattr(g, "request_params", None) is not None
Пример #23
0
def register_plugin_assets_directory(app, base_path, admins_only=False):
    """
    Registers a directory to serve assets

    :param app: A CTFd application
    :param string base_path: The path to the directory
    :param boolean admins_only: Whether or not the assets served out of the directory should be accessible to the public
    :return:
    """
    base_path = base_path.strip('/')

    def assets_handler(path):
        return send_from_directory(base_path, path)

    rule = '/' + base_path + '/<path:path>'
    app.add_url_rule(rule=rule, endpoint=base_path, view_func=assets_handler)
Пример #24
0
 def __init__(self, *args, **kwargs):
     super(ShibbolethAuthProvider, self).__init__(*args, **kwargs)
     # convert everything to lowercase (headers/WSGI vars are case-insensitive)
     self.attrs_prefix = self.settings.setdefault('attrs_prefix',
                                                  'ADFS_').lower()
     self.attrs = [attr.lower() for attr in self.settings.get('attrs')]
     if not self.settings.get('callback_uri'):
         raise MultipassException(
             "`callback_uri` must be specified in the provider settings",
             provider=self)
     self.from_headers = self.settings.get('from_headers', False)
     self.shibboleth_endpoint = '_flaskmultipass_shibboleth_' + self.name
     current_app.add_url_rule(self.settings['callback_uri'],
                              self.shibboleth_endpoint,
                              self._shibboleth_callback,
                              methods=('GET', 'POST'))
    def init_app(self, app, **kwargs):
        self.app = app
        self.kwargs.update(kwargs)
        if not hasattr(app, "extensions"):
            app.extensions = {}
        if "discoverer" in app.extensions:
            raise RuntimeError("Flask application already initialized")
        app.extensions["discoverer"] = self
        config = app.config

        for k, v in DEFAULT_CONFIG.iteritems():
            config.setdefault(k, v)
            if k in self.kwargs:
                config.update({k: self.kwargs[k]})

        route = config["DISCOVERER_PUBLISH_ENDPOINT"]
        with self.app.app_context():
            current_app.add_url_rule(route, route, lambda: self.find_resources(config["DISCOVERER_SELF_PUBLISH"]))
Пример #26
0
def register_plugin_asset(app, asset_path, admins_only=False):
    """
    Registers an file path to be served by CTFd

    :param app: A CTFd application
    :param string asset_path: The path to the asset file
    :param boolean admins_only: Whether or not this file should be accessible to the public
    :return:
    """
    asset_path = asset_path.strip('/')

    def asset_handler():
        return send_file(asset_path)

    if admins_only:
        asset_handler = admins_only_wrapper(asset_handler)
    rule = '/' + asset_path
    app.add_url_rule(rule=rule, endpoint=asset_path, view_func=asset_handler)
Пример #27
0
 def __init__(self, *args, **kwargs):
     super(AuthlibAuthProvider, self).__init__(*args, **kwargs)
     callback_uri = self.settings.get(
         'callback_uri', '/multipass/authlib/{}'.format(self.name))
     self.authlib_client = _authlib_oauth.register(self.name,
                                                   **self.authlib_settings)
     self.include_token = self.settings.get('include_token', False)
     self.use_id_token = self.settings.get('use_id_token')
     if self.use_id_token is None:
         # default to using the id token when using the openid scope (oidc)
         client_kwargs = self.authlib_settings.get('client_kwargs', {})
         scopes = client_kwargs.get('scope', '').split()
         self.use_id_token = 'openid' in scopes
     self.authorized_endpoint = '_flaskmultipass_authlib_' + self.name
     current_app.add_url_rule(callback_uri,
                              self.authorized_endpoint,
                              self._authorize_callback,
                              methods=('GET', 'POST'))
Пример #28
0
def index():
    with WebPage(default_url="index") as page:
        for c in classes:
            with page.add_child(
                    WebA(href="{{url_for('" + c[0].__name__.lower() +
                         "')}}")) as a:
                with a.add_child(WebBtn(value=c[0].__name__)) as btn:
                    pass
            current_app.add_url_rule('/' + c[0].__name__,
                                     endpoint=c[0].__name__.lower(),
                                     view_func=c[1])
            current_app.add_url_rule('/' + c[0].__name__ + '_post',
                                     endpoint=c[0].__name__.lower() + '_post',
                                     view_func=c[2],
                                     methods=['POST'])
    html = page.render()
    print(pprint.pformat(html))
    return render_template_string(html)
Пример #29
0
def _add_url_rule(url_or_urls):
    """Register url rule to application url map."""
    old = current_app._got_first_request
    # This is bit of cheating to overcome @flask.app.setupmethod decorator.
    current_app._got_first_request = False
    if isinstance(url_or_urls, six.string_types):
        url_or_urls = [url_or_urls]
    map(lambda url: current_app.add_url_rule(url, 'pages.view', view),
        url_or_urls)
    current_app._got_first_request = old
Пример #30
0
def _add_url_rule(url_or_urls):
    """Register url rule to application url map."""
    old = current_app._got_first_request
    # This is bit of cheating to overcome @flask.app.setupmethod decorator.
    current_app._got_first_request = False
    if isinstance(url_or_urls, six.string_types):
        url_or_urls = [url_or_urls]
    map(lambda url: current_app.add_url_rule(url, 'pages.view', view),
        url_or_urls)
    current_app._got_first_request = old
Пример #31
0
def handle_middleware():
  from flask import current_app as app

  # Set CORS
  CORS(app=app, resources={
    r"*": { "origin": "*" }
  })
  
  # Set GraphQL
  from app.gql import schema
  
  app.add_url_rule(
    '/graphql',
    view_func=GraphQLView.as_view(
      'graphql',
      schema=schema,
      graphiql=True
    )
  )
Пример #32
0
def test_add_request_id(client, dummy_api):
    def test_route_1():
        return "OK", 200

    endpoint = "/"
    current_app.add_url_rule(endpoint,
                             test_route_1.__name__,
                             view_func=test_route_1)
    assert getattr(g, "request_id", None) is None
    client.get(endpoint)
    dummy_api()._add_request_id()
    first_request_id = getattr(g, "request_id", None)
    assert first_request_id is not None
    uuid.UUID(str(first_request_id))
    client.get(endpoint)
    dummy_api()._add_request_id()
    second_request_id = getattr(g, "request_id", None)
    uuid.UUID(str(second_request_id))
    assert str(first_request_id) != str(second_request_id)
    def init_app(self, app, **kwargs):
        self.app = app
        self.kwargs.update(kwargs)
        if not hasattr(app, 'extensions'):
            app.extensions = {}
        if 'discoverer' in app.extensions:
            raise RuntimeError("Flask application already initialized")
        app.extensions['discoverer'] = self
        config = app.config

        for k, v in DEFAULT_CONFIG.items():
            config.setdefault(k, v)
            if k in self.kwargs:
                config.update({k: self.kwargs[k]})

        route = config['DISCOVERER_PUBLISH_ENDPOINT']
        with self.app.app_context():
            current_app.add_url_rule(
                route, route,
                lambda: self.find_resources(config['DISCOVERER_SELF_PUBLISH']))
Пример #34
0
def register_plugin_asset(app, asset_path, admins_only=False, endpoint=None):
    """
    Registers an file path to be served by KMActf

    :param app: A KMActf application
    :param string asset_path: The path to the asset file
    :param boolean admins_only: Whether or not this file should be accessible to the public
    :return:
    """
    asset_path = asset_path.strip("/")
    if endpoint is None:
        endpoint = asset_path.replace("/", ".")

    def asset_handler():
        return send_file(asset_path)

    if admins_only:
        asset_handler = admins_only_wrapper(asset_handler)
    rule = "/" + asset_path
    app.add_url_rule(rule=rule, endpoint=endpoint, view_func=asset_handler)
Пример #35
0
def test_index(monkeypatch, app_context, dummy_api, dummy_schema,
               dummy_service):
    def test_route_1():
        return "OK", 200

    assert test_route_1() == ("OK", 200)

    endpoint = "/"
    current_app.add_url_rule(endpoint,
                             test_route_1.__name__,
                             view_func=test_route_1,
                             methods=["GET"])

    schema = dummy_schema
    service = dummy_service
    api = dummy_api(schema=schema)

    monkeypatch.setattr("app.api.base.BaseAPI._service",
                        lambda *x, **y: service)
    monkeypatch.setattr("app.api.service.BaseService.list",
                        lambda *x, **y: None)
    monkeypatch.setattr(
        "app.api.response.APIResponse.create_paginated_response",
        lambda *x, **y: None)

    # Unwrap the use_args() decorator
    index = api.index
    _index = inspect.unwrap(index)

    # Happy flow
    args = dict(items_per_page=5, page_index=1)

    response = _index(api, args)

    assert response is None

    # Missing page and start index
    args = dict(items_per_page=5, )

    with pytest.raises(BadRequestError):
        _index(api, args)
Пример #36
0
def load_views():
    """
    Loads the views into the current flask app
    """

    logging.info('Loading views')

    from flask import current_app
    from service.decorators import view

    view_details = view.view_book.views
    for view_url in view_details:
        details = view_details[view_url]

        logging.info('Registering view url rule; Url: %s; View: %s' %
                     (view_url, details.view_name))

        current_app.add_url_rule(view_url,
                                 view_func=details.view_cls.as_view(
                                     details.view_name),
                                 **details.kwargs)
Пример #37
0
def register_plugin_assets_directory(app,
                                     base_path,
                                     admins_only=False,
                                     endpoint=None):
    """
    Registers a directory to serve assets

    :param app: A KMActf application
    :param string base_path: The path to the directory
    :param boolean admins_only: Whether or not the assets served out of the directory should be accessible to the public
    :return:
    """
    base_path = base_path.strip("/")
    if endpoint is None:
        endpoint = base_path.replace("/", ".")

    def assets_handler(path):
        return send_from_directory(base_path, path)

    rule = "/" + base_path + "/<path:path>"
    app.add_url_rule(rule=rule, endpoint=endpoint, view_func=assets_handler)
Пример #38
0
def _add_url_rule(url_or_urls):
    """Register URL rule to application URL map."""
    old = current_app._got_first_request
    # This is bit of cheating to overcome @flask.app.setupmethod decorator.
    current_app._got_first_request = False
    if isinstance(url_or_urls, six.string_types):
        url_or_urls = [url_or_urls]
    map(
        lambda url: current_app.add_url_rule(
            url, 'weko_gridlayout.view_widget_page', view_widget_page),
        url_or_urls)
    current_app._got_first_request = old
Пример #39
0
def proxy(proxy_url, url, **options):
    """
    Generates an app route pointing to the same relative url as the specified
    proxy url. Doesn't return anything, only add the route.
    """
    view_name = url.strip('/').replace('/<>', '_')
    def view(*args, **kwargs):
        request_func = getattr(requests, request.method.lower())
        view_url = urlparse.urljoin(proxy_url, request.path)
        data = request.form \
                if request.method.lower() in ['put', 'post'] \
                else request.data
        try:
            r = request_func(view_url, headers=request.headers, data=data)
        except requests.ConnectionError:
            abort(404)
        else:
            resp = make_response(r.content)
            resp.headers['Content-type'] = r.headers['Content-type']
            resp.status_code = r.status_code
            return resp
    current_app.add_url_rule(url, view_name, view_func=view, **options)
Пример #40
0
def test_add_params(client, dummy_api):
    def test_route_1():
        return "OK", 200

    endpoint = "/"
    current_app.add_url_rule(endpoint,
                             test_route_1.__name__,
                             view_func=test_route_1)

    data = dict(a="1", b="2")

    assert getattr(g, "request_params", None) is None
    client.get(endpoint, query_string=data)
    dummy_api()._add_params()
    assert g.request_params == data

    # Test request_params is not None
    g.request_params == data
    changed_data = dict(c="3")
    client.get(endpoint, query_string=changed_data)
    dummy_api()._add_params()
    assert g.request_params == data
Пример #41
0
def add_resource(app, resource, pk='pk'):
    uri, endpoint, view_func = get_args(resource)

    app.add_url_rule(uri, defaults={pk: None},
                     view_func=view_func, methods=['GET'])
    app.add_url_rule(uri, view_func=view_func, methods=['POST'])
    app.add_url_rule('%s<%s>/' % (uri, pk), view_func=view_func,
                     methods=['GET', 'PUT', 'PATCH', 'DELETE'])
Пример #42
0
    def _register_commands(self, plugin):
        for name in dir(plugin):
            method = getattr(plugin, name)
            if callable(method) and hasattr(method, 'is_cmd'):
                commands = [method.cmd_name]
                if method.aliases is not None:
                    aliases = method.aliases
                    if isinstance(method.aliases, basestring):
                        aliases = [method.aliases]
                    for alias in aliases:
                        commands.append(alias)

                for cmd_name in commands:
                    cmd = '!' + cmd_name
                    if cmd in self.commands:
                        raise DuplicateCommandError(cmd_name)
                    self.log.info("Registered command %s", type(plugin).__name__ + '.' + cmd_name)
                    self.commands[cmd] = PluginCommand(method)
            elif callable(method) and hasattr(method, 'is_webhook'):
                self.log.info("Registered webhook %s", type(plugin).__name__ + '.' + name)
                webhook = WebhookCommand(method, method.form_params)
                with plugin._bot.webserver.app.app_context():
                    current_app.add_url_rule(method.route, method.__name__, webhook.execute, methods=[method.method])
Пример #43
0
def result_route(func):
    current_app.add_url_rule(
        '/' + func.__name__,
        view_func=return_route_function(func),
        methods=['GET', 'POST'])
Пример #44
0
from unsubscribes import Unsubscribes


app = flask.Flask(__name__)


# Config Mongo
mongo = db.establish_mongo_connection(app)
app.mongo = mongo

# Config secret key
app.secret_key = settings.secret_key

# Routes
app.add_url_rule('/adminnew',
				view_func=Admin.as_view('admin'),
				methods=["GET", "POST"])
app.add_url_rule('/adminnew/users',
				view_func=Users.as_view('users'),
				methods=["GET", "POST"])
app.add_url_rule('/adminnew/transactions',
				view_func=UserTransactions.as_view('transactions'),
				methods=["GET"])
app.add_url_rule('/adminnew/cronjobs',
				view_func=Cronjobs.as_view('cronjobs'),
				methods=["GET"])
app.add_url_rule('/adminnew/emails',
				view_func=Emails.as_view('emails'),
				methods=["GET"])
app.add_url_rule('/adminnew/unsubscribes',
				view_func=Unsubscribes.as_view('unsubscribes'),
Пример #45
0
from flask import current_app

from myhoard.api import landingpage
from myhoard.apps.auth.oauth.views import oauth
from myhoard.apps.auth.views import UserList, UserDetails
from myhoard.apps.collections.views import CollectionDetails, CollectionList, \
    CollectionItemList, CollectionCommentList, UserPublicCollectionList
from myhoard.apps.collections.items.views import ItemDetails, ItemList
from myhoard.apps.media.views import MediaDetails, MediaList
from myhoard.apps.collections.comments.views import CommentDetails, CommentList

# Top scope urls
current_app.add_url_rule('/', view_func=landingpage, methods=['GET'])
current_app.add_url_rule('/oauth/token/', view_func=oauth, methods=['POST'])

# Blueprint urls
current_app.api.add_resource(UserList, '/users/')
current_app.api.add_resource(UserDetails, '/users/<ObjectId:user_id>/')
current_app.api.add_resource(UserPublicCollectionList, '/users/<ObjectId:user_id>/collections/')

current_app.api.add_resource(CollectionDetails, '/collections/<ObjectId:collection_id>/')
current_app.api.add_resource(CollectionList, '/collections/')
current_app.api.add_resource(CollectionItemList, '/collections/<ObjectId:collection_id>/items/')
current_app.api.add_resource(CollectionCommentList, '/collections/<ObjectId:collection_id>/comments/')

current_app.api.add_resource(ItemDetails, '/items/<ObjectId:item_id>/')
current_app.api.add_resource(ItemList, '/items/')

current_app.api.add_resource(MediaDetails, '/media/<ObjectId:media_id>/', '/media/<ObjectId:media_id>/thumbnail')
current_app.api.add_resource(MediaList, '/media/')
Пример #46
0
def make_index(app, resource, pk='pk'):
    uri, endpoint, view_func = get_args(resource)

    app.add_url_rule(uri, defaults={pk: None},
                     view_func=view_func, methods=['GET'])
def loadViews():
    from flask import current_app
    current_app.add_url_rule('/_rsa', view_func=Rsa.as_view('rsa'))
    current_app.add_url_rule('/_rsa/id', view_func=RsaId.as_view('rsaid'))
Пример #48
0
    def dispatch_request(self):
        return render_template_string(stuff)


def create_app(package_name, settings=None):

    app = Flask(package_name, template_folder='templates')

    if settings is not None:
        app.config.from_object(settings)

    return app


if __name__ == '__main__':
    app = create_app(__name__)

    # Runs perfect
    # app.add_url_rule('/hello', view_func = MyClass.as_view('my_function'))

    # Causes the context error
    current_app.add_url_rule('/hello', view_func = MyClass.as_view('my_function'))

    """ EXAMPLE ERROR
    raise RuntimeError('working outside of application context')
        RuntimeError: working outside of application context
    """

    app.run(debug=True)
Пример #49
0
 def setup_url_rules(self):
     """Configure URL rules."""
     from . import view
     app.add_url_rule('/account/<name>/update/gravatar/set',
                      view_func=view.set_gravatar)
Пример #50
0
Файл: route.py Проект: aip/phics
from flask import current_app

current_app.add_url_rule('/favicon.ico', 'favicon', lambda: current_app.send_static_file('common/favicon.ico'))
Пример #51
0
def init_views():
    from photogal.graphql import schema
    enable_graphiql = app.env == 'development'
    app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=enable_graphiql))
    app.add_url_rule('/graphql/batch', view_func=GraphQLView.as_view('graphql-batch', schema=schema, batch=True))
Пример #52
0
    def register(cls, app, route_base=None, subdomain=None, route_prefix=None,
                 trailing_slash=None):
        """Registers a FlaskView class for use with a specific instance of a
        Flask app. Any methods not prefixes with an underscore are candidates
        to be routed and will have routes registered when this method is
        called.

        :param trailing_slash:
        :param app: an instance of a Flask application

        :param route_base: The base path to use for all routes registered for
                           this class. Overrides the route_base attribute if
                           it has been set.

        :param subdomain:  A subdomain that this registration should use when
                           configuring routes.

        :param route_prefix: A prefix to be applied to all routes registered
                             for this class. Precedes route_base. Overrides
                             the class' route_prefix if it has been set.
        """

        if cls is FlaskView:
            raise TypeError("cls must be a subclass of FlaskView, not FlaskView itself")

        if route_base:
            cls.orig_route_base = cls.route_base
            cls.route_base = route_base

        if route_prefix:
            cls.orig_route_prefix = cls.route_prefix
            cls.route_prefix = route_prefix

        if not subdomain:
            if hasattr(app, "subdomain") and app.subdomain is not None:
                subdomain = app.subdomain
            elif hasattr(cls, "subdomain"):
                subdomain = cls.subdomain

        if trailing_slash is not None:
            cls.orig_trailing_slash = cls.trailing_slash
            cls.trailing_slash = trailing_slash

        members = get_interesting_members(FlaskView, cls)
        special_methods = ["get", "show", "put", "patch", "create", "update" "post", "delete", "index"]

        for name, value in members:
            proxy = cls.make_proxy_method(name)
            route_name = cls.build_route_name(name)
            try:
                if hasattr(value, "_rule_cache") and name in value._rule_cache:
                    for idx, cached_rule in enumerate(value._rule_cache[name]):
                        rule, options = cached_rule
                        rule = cls.build_rule(rule)
                        sub, ep, options = cls.parse_options(options)

                        if not subdomain and sub:
                            subdomain = sub

                        if ep:
                            endpoint = ep
                        elif len(value._rule_cache[name]) == 1:
                            endpoint = route_name
                        else:
                            endpoint = "%s_%d" % (route_name, idx,)

                        app.add_url_rule(rule, endpoint, proxy, subdomain=subdomain, **options)

                elif name in special_methods:
                    if name in ["get", "index", "show"]:
                        methods = ["GET"]
                    elif name in ['create']:
                        methods = ["POST"]
                    elif name in ['update']:
                        methods = ["PATCH", "PUT"]
                    else:
                        methods = [name.upper()]

                    rule = cls.build_rule("/", value)
                    if not cls.trailing_slash:
                        rule = rule.rstrip("/")
                    app.add_url_rule(rule, route_name, proxy, methods=methods, subdomain=subdomain)

                else:
                    route_str = '/%s/' % name
                    if not cls.trailing_slash:
                        route_str = route_str.rstrip('/')
                    rule = cls.build_rule(route_str, value)
                    app.add_url_rule(rule, route_name, proxy, subdomain=subdomain)
            except DecoratorCompatibilityError:
                raise DecoratorCompatibilityError("Incompatible decorator detected on %s in class %s" % (name, cls.__name__))

        if hasattr(cls, "orig_route_base"):
            cls.route_base = cls.orig_route_base
            del cls.orig_route_base

        if hasattr(cls, "orig_route_prefix"):
            cls.route_prefix = cls.orig_route_prefix
            del cls.orig_route_prefix

        if hasattr(cls, "orig_trailing_slash"):
            cls.trailing_slash = cls.orig_trailing_slash
            del cls.orig_trailing_slash
Пример #53
0
 def activate(self):
     current_app.add_url_rule('/report/{}/'.format(self.url_name), "report.{}".format(self.url_name), self.view)