def reverse_werkzeug_url(url, values): rule = Rule(url) # Rule needs to be bound before building m = RuleMap([rule]) # Note: this seems to be changing in Werkzeug master domain_part, url = rule.build(values) return url
def __init__(self, *args, **kwargs): """ :param view_func: a view function. """ # Setup OPTIONS parameter methods = kwargs.pop("methods", ("GET",)) provide_automatic_options = False if "OPTIONS" not in methods: methods = tuple(methods) + ("OPTIONS",) provide_automatic_options = True kwargs["methods"] = methods self.provide_automatic_options = provide_automatic_options # Set the view function endpoint = kwargs.get("endpoint", None) view_func = kwargs.pop("view_func", None) if not view_func: if callable(endpoint): view_func = endpoint endpoint = endpoint.__name__ elif type(endpoint) is str: view_func = import_string(endpoint) self.view_func = view_func kwargs["endpoint"] = endpoint RuleBase.__init__(self, *args, **kwargs)
def define_routes(cls): for route in cls.routes: rule = Rule(cls.endpoint + route['route'], endpoint=cls.endpoint + '/' + route['view_function'], methods=route['methods'], strict_slashes=False) rule.route = route app.view_functions[cls.endpoint + '/' + route['view_function']] = getattr(cls, route['view_function']) app.url_map.add(rule) return cls.routes
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index .. versionchanged:: 0.2 `view_func` parameter added. .. versionchanged:: 0.6 `OPTIONS` is added automatically as method. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (`GET`, `POST` etc.). By default a rule just listens for `GET` (and implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is implicitly added and handled by the standard request handling. """ if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options['endpoint'] = endpoint methods = options.pop('methods', ('GET',)) provide_automatic_options = False if 'OPTIONS' not in methods: methods = tuple(methods) + ('OPTIONS',) provide_automatic_options = True rule = Rule(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options self.url_map.add(rule) if view_func is not None: self.view_functions[endpoint] = view_func
def test_rule_emptying(): """Rule emptying""" r = Rule("/foo", {"meh": "muh"}, "x", ["POST"], False, "x", True, None) r2 = r.empty() assert r.__dict__ == r2.__dict__ r.methods.add("GET") assert r.__dict__ != r2.__dict__ r.methods.discard("GET") r.defaults["meh"] = "aha" assert r.__dict__ != r2.__dict__
def test_rule_emptying(): """Rule emptying""" r = Rule('/foo', {'meh': 'muh'}, 'x', ['POST'], False, 'x', True, None) r2 = r.empty() assert r.__dict__ == r2.__dict__ r.methods.add('GET') assert r.__dict__ != r2.__dict__ r.methods.discard('GET') r.defaults['meh'] = 'aha' assert r.__dict__ != r2.__dict__
def __init__(self, string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, redirect_to=None, permission=None, template=None, func=None, authRequired=False, expires=None, mimetype=None, nocache=False): Rule.__init__(self, string, defaults, subdomain, methods, build_only, endpoint, strict_slashes, redirect_to) self.permission = permission self.template = template self.func = func self.authRequired = authRequired self.expires = expires self.mimetype = mimetype self.nocache = nocache
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): assert view_func is not None, 'view_func is mandatory' if endpoint is None: endpoint = view_func.__name__ options['endpoint'] = endpoint # supposed to be GET methods = set(('GET', )) provide_automatic_options = False rule = Rule(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options self.url_map.add(rule) if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError('View function mapping is overwriting an ' 'existing endpoint function: %s' % endpoint) self.view_functions[endpoint] = view_func
def match(self, path): values = Rule.match(self, path) if values is not None: values['authRequired'] = self.authRequired values['permission'] = self.permission values['template'] = self.template values['func'] = self.func values['expires'] = self.expires values['mimetype'] = self.mimetype values['nocache'] = self.nocache return values
def __new__(cls, name, bases, attrs): # Add a url_map to the class url_map = UrlMap(strict_slashes=False) # Add a collection of (unbound) view functions view_functions = {} for base in bases: # Extend from url_map of base class if hasattr(base, 'url_map') and isinstance(base.url_map, UrlMap): for rule in base.url_map.iter_rules(): url_map.add(rule.empty()) # Extend from view_functions of base class if hasattr(base, 'view_functions') and isinstance(base.view_functions, dict): view_functions.update(base.view_functions) for routeattr, route in attrs.items(): if isinstance(route, _NodeRoute): # For wrapped routes, add a rule for each layer of wrapping endpoints = [] while isinstance(route, _NodeRoute): # Save the endpoint name endpoints.append(route.endpoint) # Construct the url rule url_rule = UrlRule(route.rule, endpoint=route.endpoint, methods=route.methods, defaults=route.defaults) url_rule.provide_automatic_options = True url_map.add(url_rule) route = route.f # Make a list of endpoints for e in endpoints: view_functions[e] = route # Restore the original function attrs[routeattr] = route # Finally, update the URL map and insert it into the class url_map.update() attrs['url_map'] = url_map attrs['view_functions'] = view_functions return type.__new__(cls, name, bases, attrs)
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
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("/create", endpoint="new_url"), Rule("/list", endpoint="list_url"), Rule("/<short_id>", endpoint="follow_short_link"), Rule("/<short_id>_details", endpoint="short_link_details"), Rule("/log_out", endpoint="exit") ])
def __init__(self, routes): rules = [] name_lookups = {} for path, name, route in self.walk_routes(routes): path_params = [ item.strip('{}') for item in re.findall('{[^}]*}', path) ] args = inspect.signature(route.handler).parameters for path_param in path_params: if path_param.startswith('+'): path = path.replace( '{%s}' % path_param, "<path:%s>" % path_param.lstrip('+') ) elif path_param in args and args[path_param].annotation is int: path = path.replace( '{%s}' % path_param, "<int:%s>" % path_param ) elif path_param in args and args[path_param].annotation is float: path = path.replace( '{%s}' % path_param, "<float:%s>" % path_param ) else: path = path.replace( '{%s}' % path_param, "<string:%s>" % path_param ) rule = Rule(path, methods=[route.method], endpoint=name) rules.append(rule) name_lookups[name] = route self.adapter = Map(rules).bind('') self.name_lookups = name_lookups # Use an MRU cache for router lookups. self._lookup_cache = dict_type() self._lookup_cache_size = 10000
def __init__(self): """ constructor url -> method mapping goes here """ # maps urls to methods self.url_map = Map([ Rule('/debug', endpoint="debug"), Rule('/playlist', endpoint="playlist"), Rule('/playlist_songs', endpoint="playlist_songs"), Rule('/share', endpoint="share"), Rule('/song', endpoint="song"), Rule('/user', endpoint="user") ])
def __init__(self, store, username, password, realm_name): self.store = store self.username = username self.password = password self.realm_name = realm_name self.router = Map([ Rule("/<key>", methods=["GET"], endpoint="get"), Rule("/", methods=["GET"], endpoint="get_list"), Rule("/<key>", methods=["PUT"], endpoint="put"), Rule("/", methods=["PUT"], endpoint="put_list"), Rule("/<key>", methods=["DELETE"], endpoint="delete"), Rule("/", methods=["DELETE"], endpoint="delete_list"), ], encoding_errors="strict")
def jsonresolver_loader(url_map): """Resolve the referred Patron for a Borrowing Request record.""" from flask import current_app @get_pid_or_default(default_value=dict()) def borrowing_request_resolver(request_pid): """Return the Patron record for the given Brw Request or raise.""" request_record_cls = current_ils_ill.borrowing_request_record_cls patron_pid = get_field_value(request_record_cls, request_pid, "patron_pid") Patron = current_app_ils.patron_cls patron = Patron.get_patron(patron_pid) return patron.dumps_loader() url_map.add( Rule( "/api/resolver/ill/borrowing-requests/<request_pid>/patron", endpoint=borrowing_request_resolver, host=current_app.config.get("JSONSCHEMAS_HOST"), ))
class ListResourceMixin(Resource): """ Resource Mixin that provides the list action for your endpoint. """ rules = [Rule('/', methods=['GET'], endpoint='list')] def list(self, request): """ Returns the list of documents found on the collection """ pipeline = [{'$match': request.args.pop('match', {})}] sort = request.args.pop('sort', {}) if sort: pipeline.append({'$sort': sort}) project = request.args.pop('project', {}) if project: pipeline.append({'$project': project}) return Response(serialize(self.collection.aggregate(pipeline)))
def jsonresolver_loader(url_map): """Resolve the referred Location for an Internal Location record.""" from flask import current_app @get_pid_or_default(default_value=dict()) def location_resolver(internal_loc_pid): """Return the Location record for the given Internal Loc. or raise.""" location_pid = get_field_value(InternalLocation, internal_loc_pid, "location_pid") location = Location.get_record_by_pid(location_pid) del location["$schema"] return location url_map.add( Rule( "/api/resolver/internal-locations/<internal_loc_pid>/location", endpoint=location_resolver, host=current_app.config.get("JSONSCHEMAS_HOST"), ) )
def __init__(self, jsonConfDir, tmpConfDir, tablePath, auxTablePath, serNode, storage): self.url_map = [] self.url_map.append(Rule('/admin/deploy', endpoint=self.deploy)) self.url_map.append(Rule('/admin/get_status', endpoint=self.get_status)) self.url_map.append(Rule('/admin/reload', endpoint=self.reload)) self.url_map.append(Rule('/admin/diff', endpoint=self.diff)) self.url_map.append(Rule('/admin/recover', endpoint=self.recover)) self.url_map.append( Rule('/admin/reload_latest', endpoint=self.reload_latest)) self.url_map.append(Rule('/admin/heartbeats', endpoint=self.heartbeats)) self.jsonConfDir = jsonConfDir self.tmpConfDir = tmpConfDir self.tablePath = tablePath self.auxTablePath = auxTablePath self.serverNode = serNode self.storage = storage
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() ]) if frappe.local.request: 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
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/'
class Web(WebServiceInterface): url_map = Map([ Rule("/test/", endpoint="test"), Rule("/foo/", endpoint=RuleHandler, methods=['get']), Rule("/baz/", endpoint=RuleHandler), HandledRule("/bar/", endpoint="bar", handler=HandledRuleHandler), Rule("/fail/", endpoint="fail"), Rule("/fail-wrong-endpoint/", endpoint=42), Rule("/bad-handler-return-type/", endpoint='return_none') ]) def test(self, request): return Response("method test") def return_none(self, request): pass
def _create_service_map(service: ServiceModel) -> Map: """ Creates a Werkzeug Map object with all rules necessary for the specific service. :param service: botocore service model to create the rules for :return: a Map instance which is used to perform the in-service operation routing - """ ops = [ service.operation_model(op_name) for op_name in service.operation_names ] rules = [] # group all operations by their path and method path_index: Dict[(str, str), List[_HttpOperation]] = defaultdict(list) for op in ops: http_op = _HttpOperation.from_operation(op) path_index[(http_op.path, http_op.method)].append(http_op) # create a matching rule for each (path, method) combination for (path, method), ops in path_index.items(): # translate the requestUri to a Werkzeug rule string rule_string = _request_uri_path_to_rule_string(path) if len(ops) == 1: # if there is only a single operation for a (path, method) combination, # the default Werkzeug rule can be used directly (this is the case for most rules) op = ops[0] rules.append( Rule(rule_string, methods=[method], endpoint=op.operation)) # type: ignore else: # if there is an ambiguity with only the (path, method) combination, # a custom rule - which can use additional request metadata - needs to be used rules.append( _RequestMatchingRule(rule_string, methods=[method], operations=ops)) return Map(rules=rules)
def add_view(self, url, name, methods=['GET'], resource=None, resource_get=None, resource_put=None, resource_post=None, resource_delete=None, template=None, acl_get='load', acl_put='update', acl_post='create', acl_delete='delete', accept=None, accept_get=None, accept_put=None, accept_post=None, accept_delete=None): """ Add and configure a view. """ self.url_map.add(Rule(url, endpoint=name)) self.view_map[name] = { "methods": [m.lower() for m in methods], "resource": resource, "resource_get": resource_get, "resource_put": resource_put, "resource_post": resource_post, "resource_delete": resource_delete, "acl_get": acl_get, "acl_put": acl_put, "acl_post": acl_post, "acl_delete": acl_delete, "accept": accept, "accept_get": accept_get, "accept_put": accept_put, "accept_post": accept_post, "accept_delete": accept_delete, "template": template }
def match(environ): map = Map() index = {} for item in web.destinations: # Lets create an index on routes, as urls.match returns a route index[item.endpoint] = item # Create the rule and add it tot he map rule = Rule(item.route, endpoint=item.endpoint, methods=item.methods) map.add(rule) # Check for match urls = map.bind_to_environ(environ) endpoint, args = urls.match() # Get match and attach current args match = index[endpoint] match.args = args return match
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", )
def jsonresolver_loader(url_map): """Resolve the referred Library for a Borrowing Request record.""" from flask import current_app @get_pid_or_default(default_value=dict()) def borrowing_request_resolver(request_pid): """Return the Library record for the given Brw Request or raise.""" request_record_cls = current_ils_ill.borrowing_request_record_cls library_pid = get_field_value(request_record_cls, request_pid, "library_pid") library_record_cls = current_ils_ill.library_record_cls library = library_record_cls.get_record_by_pid(library_pid) return pick(library, "pid", "name") url_map.add( Rule( "/api/resolver/ill/borrowing-requests/<request_pid>/library", endpoint=borrowing_request_resolver, host=current_app.config.get("JSONSCHEMAS_HOST"), ))
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'))
def __init__(self, isso, hasher): self.isso = isso self.hash = hasher.uhash self.cache = isso.cache self.signal = isso.signal self.conf = isso.conf.section("general") self.moderated = isso.conf.getboolean("moderation", "enabled") # this is similar to the wordpress setting "Comment author must have a previously approved comment" self.approve_if_email_previously_approved = isso.conf.getboolean( "moderation", "approve-if-email-previously-approved") self.trusted_proxies = list( isso.conf.getiter("server", "trusted-proxies")) self.guard = isso.db.guard self.threads = isso.db.threads self.comments = isso.db.comments for (view, (method, path)) in self.VIEWS: isso.urls.add( Rule(path, methods=[method], endpoint=getattr(self, view)))
def add_url_rule(self, rule, endpoint, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index .. versionchanged:: 0.2 `view_func` parameter added :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object """ options['endpoint'] = endpoint options.setdefault('methods', ('GET', )) self.url_map.add(Rule(rule, **options)) if view_func is not None: self.view_functions[endpoint] = view_func
class RetrieveResourceMixin(Resource): """ Resource Mixin that provides the retrieve action for your endpoint. """ rules = [Rule('/<_id>/', methods=['GET'], endpoint='retrieve')] def retrieve(self, request, _id): """ Returns the document containing the given _id or 404 """ _id = deserialize(_id) retrieved = self.collection.find_one({'_id': _id}) if retrieved: return Response(serialize(retrieved)) else: return Response( response=serialize( DocumentNotFoundError(self.collection.__name__, _id) ), status=400 )
def jsonresolver_loader(url_map): """Resolve the referred Patron for an DocumentRequest record.""" from flask import current_app def patron_resolver(document_request_pid): """Get the Patron record for the given DocumentRequest or raise.""" try: patron_pid = get_field_value( DocumentRequest, document_request_pid, "patron_pid" ) except KeyError: return {} return get_patron(patron_pid) url_map.add( Rule( "/api/resolver/document-requests/<document_request_pid>/patron", endpoint=patron_resolver, host=current_app.config.get("JSONSCHEMAS_HOST"), ) )
def add_url_rule(self, rule, endpoint, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator but does not register the view function for the endpoint. 连接一个URL规则. 类似于route装饰器做的工作,但是不会为端点(endpoint)注册视图函数 Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('index', '/') app.view_functions['index'] = index 这里示例错了,应该是 app.add_url_rule('/', 'index') 端点(endpoint)是视图函数名称, rule(规则)是'/'. :param rule: the URL rule as string # 字符串类型的URL规则 :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint 已注册URL规则的端点. Flask 本身将视图函数的名称作为一个端点. :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object 可选项,转发给底层的werkzeug.routing.Rule对象的选项 """ options['endpoint'] = endpoint options.setdefault('methods', ('GET', )) # 默认设置methods为GET self.url_map.add(Rule(rule, **options)) # 使用Werkzeug的Rule来实现规则的相关工作,具体参考博客.
def get_rules(self) -> typing.List[Rule]: """ :return: A list of :class:`werkzeug.routing.Rule` objects for this route. .. versionadded:: 2.2.0 """ rules = [] for url, methods in self.routes: # mutable list thx methods = list(methods) if "OPTIONS" not in methods: methods.append("OPTIONS") rule = Rule(url, methods=methods, host=self.bp.host if self.bp is not None else None, endpoint=self.get_endpoint_name()) rules.append(rule) return rules
class SomeApp(WebApp): def __init__(self): WebApp.__init__(self) def endpoint_some_endpoint(self, adapter, request): contract = NamedTemporaryFile() size = 0 for line in request.input_stream: contract.write(line) size += len(line) if size > 50000: return Response('too long', response='400') contract.seek(0) tmpdir = mkdtemp() results = check_output([ 'solc', contract.name, '--bin', '--abi', '--optimize', '-o', tmpdir ]) return Response('Created the following files:\n\t{}\n'.format( os.listdir(tmpdir))) url_map = Map( [Rule('/some_endpoint', endpoint='some_endpoint', methods=['POST'])])
def testTryTriggerBeforeFirstRequest(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.testCnt = 0 @app.beforeFirstRequest def doFirst(): app.testCnt = app.testCnt + 1 return app.testCnt def returnHello(*args, **kwargs): return 'Hello' app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])]) app.controllers['returnHello'] = returnHello c = app.testClient() self.assertEqual(app.testCnt, 0) c.get('/hell', content_type='text/planetext') self.assertEqual(app.testCnt, 1) c.get('/hell', content_type='text/planetext') self.assertEqual(app.testCnt, 1)
def create_app(mount_point, url_map, status=status): url_map = Map( [Rule(mount_point + path, endpoint=ep) for (path, ep) in url_map] ) def app(environ, start_response): with Request(environ) as req: try: endpoint, values = url_map.bind_to_environ(environ).match() if req.method in ('GET', 'POST'): resp = endpoint(req, **values) else: resp = status(req, 400)(environ, start_response) except NotFound: resp = status(req, 404) except BadRequestKeyError as e: # raised when indexing req.args or req.form fails print_exc() resp = status(req, 500) except HTTPException as e: resp = e return resp(environ, start_response) return app
def add_url_rule(self, rule, endpoint, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator but does not register the view function for the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('index', '/') app.view_functions['index'] = index :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object """ options['endpoint'] = endpoint options.setdefault('methods', ('GET', )) self.url_map.add(Rule(rule, **options))
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), ) ) 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-swagger-ui.yaml", endpoint=swagger_ui.serve_spec("swagger-ui", "yaml"), ), Rule( "/openapi-swagger-ui.json", endpoint=swagger_ui.serve_spec("swagger-ui", "json"), ), Rule("/openapi-doc.yaml", endpoint=swagger_ui.serve_spec("doc", "yaml")), Rule("/openapi-doc.json", endpoint=swagger_ui.serve_spec("doc", "json")), *rules, ], ), ] ) self.wsgi_app = with_context_middleware(OverrideRequestMethod(self._wsgi_app))
def decorator(f): """ Registers a function as route :param f: function :return: function Returns f """ def handle(*args, **kwargs): target = f for m in state_.middlewares: target = m(target) try: res = target(*args, **kwargs) except TypeError as e: try: if 'arguments' in str(e): res = target(**kwargs) else: res = target(*args, **kwargs) except BaseException as e: res = state_.on_error(e) if res: return res else: return '' name = str(uuid.uuid4()) rule = Rule(url, methods=methods, endpoint=name, strict_slashes=False) state_.url_map.add(rule) state_.routes[name] = { 'function': handle, 'on_error': state_.on_error, 'url': re.sub(r'<(\w*:)?(\w*)>', r':\2', url), 'docs': f.__doc__, 'methods': methods } return f
def __init__(self, endpoint, methods=['get']): Rule.__init__(self, '/', endpoint=endpoint, methods=methods)
def route_(self, rule, methods=None, werkzeug_route=None, tornado_route=None, handler_bases=None, fn=None, nowrap=None): if not methods: methods = ['GET'] clsname = '%sHandler' % fn.__name__.capitalize() # TODO: things get complicated if you use your own base class and debug=True if not handler_bases: if self.debug: bases = (DebuggableHandler,) else: bases = (tornado.web.RequestHandler,) else: bases = (DebuggableHandler,) + handler_bases m = {} for method in methods: inspected = inspect.getargspec(fn) can_be_wrapped = True if nowrap == None: # are we using a tornado.coroutine or something similar, # we dont wrap if 'tornado' in inspect.getsourcefile(fn): can_be_wrapped = False else: can_be_wrapped = nowrap != True else: can_be_wrapped = nowrap self_in_args = inspected.args and inspected.args[0] in ['self', 'handler'] if not self_in_args and can_be_wrapped==True: def wrapper(self, *args, **kwargs): with StackContext(functools.partial(ctx_man, self)) as cm: w = fn #wrap(fn) result = w(*args, **kwargs) if isinstance(result, TemplateProxy): if self._template_engine == 'tornado': self.render(*result.args, **result.kwargs) else: template = self._template_env.get_template(result.args[0]) self.finish(template.render(handler=self, **result.kwargs)) else: self.finish(result) # import gc # # gc.collect() # print "is gc enabled", gc.isenabled() # print "-----------------" # for obj in gc.get_objects(): # if isinstance(obj, DebuggableHandler): # print ">>>", type(obj), "<<<" # # print "-----------------" m[method.lower()] = wrapper else: m[method.lower()] = fn klass = type(clsname, bases, m) klass._template_engine = self.template_engine if self.template_engine != 'tornado': klass._template_env = self.template_env use_werkzeug_route = None if tornado_route: use_werkzeug_route = False if werkzeug_route: use_werkzeug_route = True if use_werkzeug_route == None: use_werkzeug_route = self.is_werkzeug_route(rule) if use_werkzeug_route: r = Rule(rule, methods=methods) self.url_map.add(r) r.compile() pattern = r._regex.pattern.replace('^\\|', "") self.registery[pattern] = klass else: self.registery[rule] = klass
def __init__(self, pattern, **kwargs): try: self.view = kwargs.pop('view') except KeyError: self.view = None OriginalRule.__init__(self, pattern, **kwargs)
def __init__(self, endpoint, url, controller): Rule.__init__(self, url, endpoint=endpoint) self.gmg_controller = controller
def __init__(self, *args, **kwargs): self.handler = kwargs.pop('handler', kwargs.get('endpoint', None)) WerkzeugRule.__init__(self, *args, **kwargs)
def __init__(self, endpoint, url, controller, match_slash=True): Rule.__init__(self, url, endpoint=endpoint) self.gmg_controller = controller self.match_slash = match_slash
def compile(self): Rule.compile(self) self._regex = re.compile(self._regex.pattern, re.UNICODE | re.IGNORECASE)
def empty(self): new_rule = Rule.empty(self) new_rule.gmg_controller = self.gmg_controller return new_rule
def __init__(self, string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, redirect_to=None, alias=False, host=None, mimetype=None): _Rule.__init__(self, string, defaults, subdomain, methods, build_only, endpoint, strict_slashes, redirect_to, alias, host) self.mimetype = mimetype