Esempio n. 1
0
    def init_routing(self):
        # setup the Map object with the appropriate settings
        self.ag.route_map = Map(**self.settings.routing.map.todict())

        # load view modules so routes from @asview() get setup correctly
        if self.settings.auto_load_views:
            visitmods('views')

        # application routes first since they should take precedence
        self.add_routing_rules(self.settings.routing.routes)

        # now the routes from component settings
        for pname in self.settings.components.keys():
            psettings = self.settings.components[pname]
            try:
                self.add_routing_rules(psettings.routes)
            except AttributeError as e:
                if "no attribute 'routes'" not in str(e):
                    raise  # pragma: no cover
Esempio n. 2
0
 def __init__(self, main_app=True, name="", base_rule="/"):
     self.url_map = Map([])
     self.view_functions = {}
     self.config = {
         # Default Config
         "hostname": 'localhost',
         "port": 8080,
         "debug": True,
         # security key for session
         "security_key": b'YgHfXTZRK1t_tTGOh139WEpEii5gkqobuD89U7er1Ls=',
     }
     # main_app for checking whether the app is considered as main app or combined to the main app
     self.main_app = main_app
     # name for namespace
     self.name = name
     # base_rule
     self.base_rule = base_rule
     # security key for session ref to config['security_key']
     self.security_key = self.config.get("security_key", b'YgHfXTZRK1t_tTGOh139WEpEii5gkqobuD89U7er1Ls=')
     # init AppGlobal
     self.app_global = AppGlobal()
     # after_app
     self._after_app = []
     # before_request
     self._before_request = []
     # after_request
     self._after_request = []
     # before_response
     self._before_response = []
     # after_response
     self._after_response = []
     # HttpExceptions view functions
     self.exception_all = None
     self.exception_400 = lambda _app, e: JSONResponse(StyledJSON(code=400, messaga="Invalid Request"))
     self.exception_401 = lambda _app, e: JSONResponse(StyledJSON(code=401, messaga="Unauthorized"))
     self.exception_403 = lambda _app, e: JSONResponse(StyledJSON(code=403, messaga="Forbidden"))
     self.exception_404 = lambda _app, e: JSONResponse(StyledJSON(code=404, messaga="Not Found"))
     self.exception_406 = lambda _app, e: JSONResponse(StyledJSON(code=406, messaga="Not Acceptable"))
     self.exception_410 = lambda _app, e: JSONResponse(StyledJSON(code=410, messaga="Gone"))
     self.exception_422 = lambda _app, e: JSONResponse(StyledJSON(code=422, messaga="Unprocessable Entity"))
     self.exception_500 = lambda _app, e: JSONResponse(StyledJSON(code=500, messaga="Internal Server Error"))
     # api help doc
     self._api_help_doc = {}
Esempio n. 3
0
def create_backend_app(service):
    from werkzeug.routing import Map

    # Create the backend_app
    backend_app = Flask(__name__)
    backend_app.debug = True
    backend_app.service = service
    CORS(backend_app)

    # Reset view functions to reset the app
    backend_app.view_functions = {}
    backend_app.url_map = Map()
    backend_app.url_map.converters["regex"] = RegexConverter
    backend = list(backends.get_backend(service).values())[0]
    for url_path, handler in backend.flask_paths.items():
        view_func = convert_flask_to_httpretty_response(handler)
        if handler.__name__ == "dispatch":
            endpoint = "{0}.dispatch".format(handler.__self__.__name__)
        else:
            endpoint = view_func.__name__

        original_endpoint = endpoint
        index = 2
        while endpoint in backend_app.view_functions:
            # HACK: Sometimes we map the same view to multiple url_paths. Flask
            # requires us to have different names.
            endpoint = original_endpoint + str(index)
            index += 1

        # Some services do not provide a URL path
        # I.e., boto3 sends a request to 'https://ingest.timestream.amazonaws.com'
        # Which means we have a empty url_path to catch this request - but Flask can't handle that
        if url_path:
            backend_app.add_url_rule(
                url_path,
                endpoint=endpoint,
                methods=HTTP_METHODS,
                view_func=view_func,
                strict_slashes=False,
            )

    backend_app.test_client_class = AWSTestHelper
    return backend_app
Esempio n. 4
0
def werkzeug(body, headers):
    import werkzeug.wrappers as werkzeug
    from werkzeug.routing import Map, Rule

    path = '/hello/<account_id>/test'
    url_map = Map([Rule(path, endpoint='hello')])

    @werkzeug.Request.application
    def hello(request):
        user_agent = request.headers['User-Agent']  # NOQA
        limit = request.args.get('limit', '10')  # NOQA
        adapter = url_map.bind_to_environ(request.environ)  # NOQA
        endpoint, values = adapter.match()  # NOQA
        aid = values['account_id']  # NOQA

        return werkzeug.Response(body, headers=headers,
                                 mimetype='text/plain')

    return hello
Esempio n. 5
0
def build_adapter(app: Flask) -> MapAdapter:
    """Build a :class:`.MapAdapter` from configured URLs."""
    # Get the base URLs (configured in this package).
    configured_urls = {url[0]: url for url in base_config.URLS}
    # Privilege ARXIV_URLs set on the application config.
    current_urls = app.config.get('URLS', [])
    if current_urls:
        configured_urls.update({url[0]: url for url in current_urls})
    url_map = Map([
        Rule(pattern, endpoint=name, host=host, build_only=True)
        for name, pattern, host in configured_urls.values()
    ],
                  converters={'arxiv': ArXivConverter},
                  host_matching=True)

    scheme = app.config.get('EXTERNAL_URL_SCHEME', 'https')
    base_host = app.config.get('BASE_SERVER', 'arxiv.org')
    adapter: MapAdapter = url_map.bind(base_host, url_scheme=scheme)
    return adapter
Esempio n. 6
0
    def __init__(self, config):
        self.redis = redis.Redis(config["redis_host"], config["redis_port"])
        template_path = os.path.join(os.path.dirname(__file__), "templates")
        self.jinja_env = Environment(
            loader=FileSystemLoader(template_path), autoescape=True)
        self.jinja_env.filters["hostname"] = get_hostname

        self.url_map = Map(
            [
                Rule("/", endpoint="sign_up"),
                Rule("/home", endpoint="home"),
                Rule("/<short_id>_details", endpoint="short_link_details"),
                Rule("/create", endpoint="new_url"),
                Rule("/<short_id>", endpoint="follow_short_link"),
                Rule("/short_link_list", endpoint="list_url"),
                Rule("/sign_in", endpoint="sign_in"),
                Rule("/sign_out", endpoint="sign_out"),
            ]
        )
Esempio n. 7
0
    def __init__(self, conf):
        if conf:
            self.conf = read_conf(conf['key_file'],
                                  section_name="admin-server")
        else:
            self.conf = {}
        self.logger = get_logger(self.conf, name="ContainerBackup")

        self.proxy = ObjectStorageApi(self.conf.get("namespace", NS),
                                      logger=self.logger)
        self.url_map = Map([
            Rule('/v1.0/container/dump', endpoint='dump'),
            Rule('/v1.0/container/restore', endpoint='restore'),
        ])
        self.REDIS_TIMEOUT = self.conf.get("redis_cache_timeout",
                                           self.REDIS_TIMEOUT)

        super(ContainerBackup, self).__init__(self.conf)
        WerkzeugApp.__init__(self, self.url_map, self.logger)
Esempio n. 8
0
def resolve_from_map(path):
    m = Map([
        Rule(r["from_route"],
             endpoint=r["to_route"],
             defaults=r.get("defaults")) for r in get_website_rules()
    ])
    urls = m.bind_to_environ(frappe.local.request.environ)
    try:
        endpoint, args = urls.match("/" + path)
        path = endpoint
        if args:
            # don't cache when there's a query string!
            frappe.local.no_cache = 1
            frappe.local.form_dict.update(args)

    except NotFound:
        pass

    return path
Esempio n. 9
0
    def __init__(self, debug: bool = False):
        self.debug = debug
        rules = []
        for endpoint in ENDPOINT_REGISTRY:
            if self.debug:
                # This helps us to make sure we can always generate a valid OpenAPI yaml file.
                _ = endpoint.to_operation_dict()

            rules.append(
                Rule(endpoint.default_path,
                     methods=[endpoint.method],
                     endpoint=Authenticate(endpoint.wrapped)))

        spec_file_buffer = spec_file()
        swagger_ui = ServeSwaggerUI(prefix="^/[^/]+/check_mk/api/[^/]+/ui")

        self.url_map = Map([
            Submount(
                "/<path:_path>",
                [
                    Rule("/ui/", endpoint=swagger_ui),
                    Rule("/ui/<path:path>", endpoint=swagger_ui),
                    Rule(
                        "/openapi.yaml",
                        endpoint=serve_content(
                            file_handle=spec_file_buffer,
                            content_type='application/x-yaml; charset=utf-8',
                        ),
                    ),
                    Rule(
                        "/openapi.json",
                        endpoint=serve_content(
                            file_handle=json_file(spec_file_buffer),
                            content_type='application/json',
                        ),
                    ),
                    *rules,
                ],
            ),
        ])
        self.wsgi_app = with_context_middleware(
            OverrideRequestMethod(self._wsgi_app))
Esempio n. 10
0
    def __init__(self, rules):
        rule_objs = []
        for rule in rules:
            endpoint_name = endpoint_regex.sub('', rule["path"])

            rule_objs.append(Rule(
                '/%s' % rule["path"],
                methods=rule["methods"],
                endpoint=endpoint_name
            ))

            # Add function into the local context
            code = compile("""def %s(request):
                print(Fore.GREEN)
                print("URL\\n----\\n{0}\\n".format(str(request.url)))
                print("Method\\n----\\n{0}\\n".format(str(request.method)))
                print("Args\\n----\\n{0}\\n".format(str(request.args)))
                print("Headers\\n-------\\n{0}\\n".format(str(request.headers)))
                print("Files\\n-----\\n{0}\\n".format(str(request.files)))
                print("Form\\n-----\\n{0}\\n".format(str(request.form)))
                print("Data\\n-----\\n{0}\\n".format(str(request.data)))
                print(Style.RESET_ALL)

                try:
                    resp = json.loads(json.dumps('%s'))
                except ValueError:
                    resp = str('%s')

                return Response(**{"mimetype": "application/json", "response": resp})
            """ % (endpoint_name, rule["response"], rule["response"]), "<string>", "exec")

            ns = {
                "json": json,
                "Fore": Fore,
                "Style": Style,
                "Response": Response,
            }
            exec(code, ns)

            self.__setattr__(endpoint_name, ns[endpoint_name])

        self.url_map = Map(rule_objs)
Esempio n. 11
0
    def __init__(self, package_name):
        print("Flask __init__ start!")
        self.debug = False  # 调试模式开关
        # 注意:
        #   - 这个参数,不是随便乱给的
        #   - 要跟实际的 项目工程目录名对应,否则无法找到对应的工程
        self.package_name = package_name
        # 注意:
        #   - 调用前面定义的 全局私有方法
        #   - 依赖前面的传入参数, 通过该参数, 获取 项目工程源码根目录.
        self.root_path = _get_package_path(self.package_name)  # 获取项目根目录
        self.view_functions = {}  # 视图函数集
        self.error_handlers = {}  # 出错处理
        self.before_request_funcs = []  # 预处理
        self.after_request_funcs = []  # 结束清理
        self.template_context_processors = [_default_template_ctx_processor]

        # todo: 待深入
        self.url_map = Map()  # 关键依赖: werkzeug.routing.Map
        if self.static_path is not None:  # 处理静态资源
            #
            # todo: 待深入 关键依赖: werkzeug.routing.Rule
            self.url_map.add(
                Rule(self.static_path + '/<filename>',
                     build_only=True,
                     endpoint='static'))

            if pkg_resources is not None:
                target = (self.package_name, 'static')
            else:
                target = os.path.join(self.root_path, 'static')

            #
            # todo: 待深入, 关键依赖: werkzeug.SharedDataMiddleware
            self.wsgi_app = SharedDataMiddleware(self.wsgi_app,
                                                 {self.static_path: target})
        # todo: 待深入, jinja2 模板配置
        self.jinja_env = Environment(loader=self.create_jinja_loader(),
                                     **self.jinja_options)
        self.jinja_env.globals.update(
            url_for=url_for, get_flashed_messages=get_flashed_messages)
        print("Flask __init__ end!")
Esempio n. 12
0
def build_rules(rules_tuples):
    """
    Given a list of tuples like this:

    [
        ('/', 'index', views.Index),
        ('/hello/<name>/', 'hello', views.Hello),
    ]

    Return two things:
        1. A Werkzeug Map object.
        2. A dictionary mapping the names of the Werkzeug endpoints to view
        classes.
    """
    handlers = {}
    rules = []
    for pat, name, view in rules_tuples:
        rules.append(Rule(pat, endpoint=name))
        handlers[name] = view
    return Map(rules), handlers
Esempio n. 13
0
def test_http_host_before_server_name():
    """URL routing HTTP host takes precedence before server name"""
    env = {
        'HTTP_HOST':            'wiki.example.com',
        'SERVER_NAME':          'web0.example.com',
        'SERVER_PORT':          '80',
        'SCRIPT_NAME':          '',
        'PATH_INFO':            '',
        'REQUEST_METHOD':       'GET',
        'wsgi.url_scheme':      'http'
    }
    map = Map([Rule('/', endpoint='index', subdomain='wiki')])
    adapter = map.bind_to_environ(env, server_name='example.com')
    assert adapter.match('/') == ('index', {})
    assert adapter.build('index', force_external=True) == 'http://wiki.example.com/'
    assert adapter.build('index') == '/'

    env['HTTP_HOST'] = 'admin.example.com'
    adapter = map.bind_to_environ(env, server_name='example.com')
    assert adapter.build('index') == 'http://wiki.example.com/'
Esempio n. 14
0
def test_basic_routing():
    """Basic URL routing"""
    map = Map([
        Rule('/', endpoint='index'),
        Rule('/foo', endpoint='foo'),
        Rule('/bar/', endpoint='bar')
    ])
    adapter = map.bind('example.org', '/')
    assert adapter.match('/') == ('index', {})
    assert adapter.match('/foo') == ('foo', {})
    assert adapter.match('/bar/') == ('bar', {})
    assert_raises(RequestRedirect, lambda: adapter.match('/bar'))
    assert_raises(NotFound, lambda: adapter.match('/blub'))

    adapter = map.bind('example.org', '/test')
    try:
        adapter.match('/bar')
    except RequestRedirect, e:
        print e.new_url
        assert e.new_url == 'http://example.org/test/bar/'
Esempio n. 15
0
    def __init__(self, conf, logger=None):
        self.conf = conf
        self.logger = logger or get_logger(self.conf)
        self.backend = XcuteBackend(self.conf, logger=self.logger)

        url_map = Map([
            Rule('/status', endpoint='status'),
            Submount('/v1.0/xcute', [
                Rule('/job/list', endpoint='job_list', methods=['GET']),
                Rule('/job/create', endpoint='job_create', methods=['POST']),
                Rule('/job/show', endpoint='job_show', methods=['GET']),
                Rule('/job/pause', endpoint='job_pause', methods=['POST']),
                Rule('/job/resume', endpoint='job_resume', methods=['POST']),
                Rule('/job/delete', endpoint='job_delete', methods=['DELETE']),
                Rule('/lock/list', endpoint='lock_list', methods=['GET']),
                Rule('/lock/show', endpoint='lock_show', methods=['GET']),
            ])
        ])

        super(XcuteServer, self).__init__(url_map, logger)
Esempio n. 16
0
    def __init__(self, config):
        self.redis = redis.Redis(config["redis_host"], config["redis_port"])
        template_path = os.path.join(os.path.dirname(__file__), "templates")
        self.jinja_env = Environment(
            loader=FileSystemLoader(template_path), autoescape=True
        )
        self.jinja_env.filters["hostname"] = get_hostname

        self.url_map = Map(
            [
                Rule("/", endpoint="home"),
                Rule("/<short_id>_details", endpoint="short_link_details"),
                Rule("/create", endpoint="new_url"),
                Rule("/<short_id>", endpoint="follow_short_link"),
                # TODO: Добавить ендпоинты на:
                # - создание шортката
                # - редирект по ссылке
                # - детальную информацию о ссылке
            ]
        )
Esempio n. 17
0
def create_url_map(debug=False):
    """Instantiate all WSGI Apps and put them into the URL-Map."""
    debug_rules = [
        Rule("/dump.py", endpoint=dump_environ_app),
        Rule("/form.py", endpoint=test_formdata),
    ]

    cmk_app = CheckmkApp()
    api_app = CheckmkRESTAPI(debug=debug).wsgi_app

    return Map([
        Submount('/<string:site>', [
            Submount("/check_mk", [
                Rule("/", endpoint=cmk_app),
                *(debug_rules if debug else []),
                Rule("/api/<string:version>/<path:path>", endpoint=api_app),
                Rule("/<string:script>", endpoint=cmk_app),
            ]),
        ])
    ])
Esempio n. 18
0
def match_endpoint(path: str) -> tuple[models.Endpoint, Mapping[str, Any]]:
    """
    Uses werkzeug routing to match the given path to an endpoint.
    Returns the matched endpoint as well as a mapping of URL parameters passed to the endpoint.
    If no endpoint was matched, raises a NotFound exception.
    """

    log.debug(f"Matching path `{path}`")

    endpoints: list[models.Endpoint] = models.Endpoint.query.filter(
        models.Endpoint.method == request.method.upper()).all()

    rules = [
        Rule(endpoint.path, endpoint=endpoint, methods=[request.method])
        for endpoint in endpoints
    ]
    urls = Map(rules).bind("localhost")

    # we're disabling mypy here because you're supposed to get strings back from `match`, not full endpoint objects.
    return urls.match(path, method=request.method)  # type: ignore
Esempio n. 19
0
def map():
    return Map(
        [
            # Static URLs
            Rule("/", endpoint="static/index"),
            Rule("/about", endpoint="static/about"),
            Rule("/help", endpoint="static/help"),
            # Knowledge Base
            Subdomain(
                "kb",
                [
                    Rule("/", endpoint="kb/index"),
                    Rule("/browse/", endpoint="kb/browse"),
                    Rule("/browse/<int:id>/", endpoint="kb/browse"),
                    Rule("/browse/<int:id>/<int:page>", endpoint="kb/browse"),
                ],
            ),
        ],
        default_subdomain="www",
    )
Esempio n. 20
0
class JsonrpcGateway(WebServiceInterface):

    url_map = Map([
        Rule('/', endpoint='index'),
        Rule('/static/<path:path>', endpoint='static_resource'),
        Rule('/api/jsonrpc/<string:service_type>/', endpoint='jsonrpc'),
    ])

    def index(self, request):
        return self.static_resource(request, path='jsonrpc.html', content_type='text/html')

    def static_resource(self, request, path=None, content_type=None):
        with open('examples/static/%s' % path) as f:
            return Response(f.read(), content_type=content_type)

    def jsonrpc(self, request, service_type):
        req = json.load(request.stream)
        args = req['params'][0]
        result = self.request(service_type, str(req['method']), args)
        return Response(json.dumps({'result': {'result': result.body, 'gateway': self.container.endpoint}, 'error': None, 'id': req['id']}), content_type='application/json')
 def __init__(self, help_handler, cancel_handler, assign_handler,
              introspect_handler):
     """Initialize the REST API
     :param help_handler: callable, a function that will be invoked when a new request for assistance arrives
     :param cancel_handler: callable, will be invoked when a request for assistance was cancelled
     :param assign_handler: callable, will be invoked when a request for assistance was assigned to someone
     :param introspect_handler: callable, invoked when you go to the /introspect URL, it simply dumps the bot's state
                                so you can get a clue about the current situation"""
     self.help_request_handler = help_handler
     self.cancel_request_handler = cancel_handler
     self.assign_request_handler = assign_handler
     self.introspect_handler = introspect_handler
     self.form = open("res/static/index.html", "rb").read()
     self.url_map = Map([
         Rule("/", endpoint="root"),
         Rule("/help_request", endpoint="help_request"),
         Rule("/cancel_help_request", endpoint="cancel_help_request"),
         Rule("/assign_help_request", endpoint="assign_help_request"),
         Rule("/introspect", endpoint="introspect_request"),
     ])
Esempio n. 22
0
def test_greedy_path_converter():
    # this test is mostly to document behavior

    router = Map(converters={"path": GreedyPathConverter}, merge_slashes=False)

    router.add(Rule("/test-bucket/<path:p>"))
    router.add(Rule("/some-route/<path:p>/bar"))

    matcher = router.bind("")
    # open-ended case
    assert matcher.match("/test-bucket//foo/bar") == (None, {"p": "/foo/bar"})
    assert matcher.match("/test-bucket//foo//bar") == (None, {"p": "/foo//bar"})
    assert matcher.match("/test-bucket//foo/bar/") == (None, {"p": "/foo/bar/"})

    # with a matching suffix
    assert matcher.match("/some-route//foo/bar") == (None, {"p": "/foo"})
    assert matcher.match("/some-route//foo//bar") == (None, {"p": "/foo/"})
    assert matcher.match("/some-route//foo/bar/bar") == (None, {"p": "/foo/bar"})
    with pytest.raises(NotFound):
        matcher.match("/some-route//foo/baz")
Esempio n. 23
0
    def __init__(self, config, duration, errors):
        self._config = config
        self._duration = duration
        self._errors = errors

        self._url_map = Map([
            Rule('/', endpoint='index'),
            Rule('/metrics', endpoint='metrics'),
            Rule('/esl', endpoint='esl'),
        ])

        self._args = {
            'esl': ['module', 'target']
        }

        self._views = {
            'index': self.on_index,
            'metrics': self.on_metrics,
            'esl': self.on_esl,
        }
Esempio n. 24
0
    def __init__(self, config, duration, errors):
        self._config = config
        self._duration = duration
        self._errors = errors

        self._url_map = Map([
            Rule('/', endpoint='index'),
            Rule('/metrics', endpoint='metrics'),
            Rule('/pve', endpoint='pve'),
        ])

        self._args = {'pve': ['module', 'target']}

        self._views = {
            'index': self.on_index,
            'metrics': self.on_metrics,
            'pve': self.on_pve,
        }

        self._log = logging.getLogger(__name__)
Esempio n. 25
0
def test_basic_building():
    map = Map([
        Rule('/', endpoint='index'),
        Rule('/foo', endpoint='foo'),
        Rule('/bar/<baz>', endpoint='bar'),
        Rule('/bar/<int:bazi>', endpoint='bari'),
        Rule('/bar/<float:bazf>', endpoint='barf'),
        Rule('/bar/<path:bazp>', endpoint='barp'),
        Rule('/hehe', endpoint='blah', subdomain='blah')
    ])
    adapter = map.bind('example.org', '/', subdomain='blah')

    assert adapter.build('index', {}) == 'http://example.org/'
    assert adapter.build('foo', {}) == 'http://example.org/foo'
    assert adapter.build('bar', {'baz': 'blub'}) == 'http://example.org/bar/blub'
    assert adapter.build('bari', {'bazi': 50}) == 'http://example.org/bar/50'
    assert adapter.build('barf', {'bazf': 0.815}) == 'http://example.org/bar/0.815'
    assert adapter.build('barp', {'bazp': 'la/di'}) == 'http://example.org/bar/la/di'
    assert adapter.build('blah', {}) == '/hehe'
    raises(BuildError, lambda: adapter.build('urks'))
Esempio n. 26
0
 def __init__(self, brubeck_object):
     super(Brubeck, self).__init__()
     # copy all brubeck object attributes to simpleurl.
     for key, val in brubeck_object.__dict__.iteritems():
         setattr(self, key, val)
     #: Werkzeug Rule class
     self.url_rule_class = Rule
     #: Map object which stores all the Rules
     self.url_map = Map()
     #: A dictionary of all view functions registered.  The keys will
     #: be function names which are also used to generate URLs and
     #: the values are the function objects themselves.
     #: To register a view function, use the :meth:`route` decorator.
     self.view_functions = {}
     # if handler_tuples add routes
     if brubeck_object.handler_tuples is not None:
         self.handler_tuples = brubeck_object.handler_tuples
     # Keep state for handler_tuples so that we needn't add routes in route_message
     # every time request is received
     self.is_handler_tuples_added = False
Esempio n. 27
0
    def __init__(self, config):
        self.redis = redis.Redis(config["redis_host"], config["redis_port"])

        template_path = os.path.join(os.path.dirname(__file__), "templates")

        self.jinja_env = Environment(
            loader=FileSystemLoader(template_path), autoescape=True
        )
        self.jinja_env.filters["hostname"] = get_hostname

        self.url_map = Map( # ROUTING
            [
                Rule("/", endpoint="home"),
                Rule("/new_url", endpoint="new_url"),
                Rule('/<short_id>/details',endpoint='short_link_details'),
                Rule('/<short_id>',endpoint='follow_short_link'),
                Rule('/list',endpoint='list_url'),
                Rule('/logout',endpoint='logout')
            ]
        )
Esempio n. 28
0
    def __init__(self, config):
        self.config = config

        for fn in listdir(path.join(path.dirname(__file__), 'views')):
            if fn.endswith('.py') and fn != '__init__.py':
                __import__('coolmagic.views.' + fn[:-3])

        from coolmagic.utils import exported_views
        rules = [
            # url for shared data. this will always be unmatched
            # because either the middleware or the webserver
            # handles that request first.
            Rule('/public/<path:file>', endpoint='shared_data')
        ]
        self.views = {}
        for endpoint, (func, rule, extra) in exported_views.iteritems():
            if rule is not None:
                rules.append(Rule(rule, endpoint=endpoint, **extra))
            self.views[endpoint] = func
        self.url_map = Map(rules)
Esempio n. 29
0
    def __init__(self, conf):
        if conf:
            self.conf = read_conf(conf['key_file'],
                                  section_name="admin-server")
        else:
            self.conf = {}
        self.logger = get_logger(self.conf, name="ContainerBackup")

        self.proxy = ObjectStorageApi(self.conf.get("namespace", NS),
                                      logger=self.logger)
        self.url_map = Map([
            Rule('/v1.0/container/dump', endpoint='dump'),
            Rule('/v1.0/container/restore', endpoint='restore'),
        ])
        self.REDIS_TIMEOUT = self.conf.get("redis_cache_timeout",
                                           self.REDIS_TIMEOUT)

        redis_conf = {
            k[6:]: v
            for k, v in self.conf.items() if k.startswith("redis_")
        }
        redis_host = redis_conf.pop('host', None)
        if redis_host:
            parsed = urlparse('http://' + redis_host)
            if parsed.port is None:
                redis_host = '%s:%s' % (redis_host,
                                        redis_conf.pop('port', '6379'))
        redis_sentinel_hosts = redis_conf.pop(
            'sentinel_hosts',
            # TODO(adu): Delete when it will no longer be used
            self.conf.get('sentinel_hosts'))
        redis_sentinel_name = redis_conf.pop(
            'sentinel_name',
            # TODO(adu): Delete when it will no longer be used
            self.conf.get('sentinel_master_name'))
        RedisConnection.__init__(self,
                                 host=redis_host,
                                 sentinel_hosts=redis_sentinel_hosts,
                                 sentinel_name=redis_sentinel_name,
                                 **redis_conf)
        WerkzeugApp.__init__(self, self.url_map, self.logger)
Esempio n. 30
0
 def __init__(self, work_dir, load_task):
     mimetypes.add_type('text/cache-manifest', '.appcache')
     self.started = datetime.datetime.now()
     self.work_dir = work_dir
     self.state = common.PROJECT_NONE
     self._load_lock = Lock()
     self.admin = None
     self.task = None
     self.privileges = None
     self._busy = 0
     self.pid = os.getpid()
     self.jam_dir = os.path.realpath(os.path.dirname(jam.__file__))
     self.jam_version = jam.version()
     self.__is_locked = 0
     self.application_files = {
         '/': self.work_dir,
         '/jam/': self.jam_dir
     }
     self.fileserver = SharedDataMiddleware(None, self.application_files, cache_timeout=1)
     self.url_map = Map([
         Rule('/', endpoint='root_file'),
         Rule('/<file_name>', endpoint='root_file'),
         Rule('/js/<file_name>', endpoint='file'),
         Rule('/css/<file_name>', endpoint='file'),
         Rule('/jam/js/<file_name>', endpoint='file'),
         Rule('/jam/js/ace/<file_name>', endpoint='file'),
         Rule('/jam/css/<file_name>', endpoint='file'),
         Rule('/jam/css/themes/<file_name>', endpoint='file'),
         Rule('/jam/img/<file_name>', endpoint='file'),
         Rule('/api', endpoint='api'),
         Rule('/upload', endpoint='upload')
     ])
     self.admin = self.create_admin()
     with self.admin.lock('$creating_task'):
         self.admin.read_settings()
         self.max_content_length = self.admin.max_content_length
         self.build_id_prefix = '$buildID'
         self.save_build_id();
         if load_task:
             self.get_task()
         self.check_migration()