Generate a ProxyClass based view that uses the passed base_url.
779484
def generate_proxy(
        prefix, base_url='', verify_ssl=True, middleware=None,
        append_middleware=None, cert=None, timeout=None):
    """"""
    middleware = list(middleware or HttpProxy.proxy_middleware)
    middleware += list(append_middleware or [])

    return type('ProxyClass', (HttpProxy,), {
        'base_url': base_url,
        'reverse_urls': [(prefix, base_url)],
        'verify_ssl': verify_ssl,
        'proxy_middleware': middleware,
        'cert': cert,
        'timeout': timeout
    })
308727
def construct_exc_class(cls):
    """"""

    class ProxyException(cls, BaseException):
        __pep3134__ = True

        @property
        def __traceback__(self):
            if self.__fixed_traceback__:
                return self.__fixed_traceback__

            current_exc, current_tb = sys.exc_info()[1:]
            if current_exc is self:
                return current_tb

        def __init__(self, instance=None):  # pylint: disable=W0231
            self.__original_exception__ = instance
            self.__fixed_traceback__ = None

        def __getattr__(self, item):
            return getattr(self.__original_exception__, item)

        def __repr__(self):
            return repr(self.__original_exception__)

        def __str__(self):
            return str(self.__original_exception__)

        def with_traceback(self, traceback):
            instance = copy.copy(self)
            instance.__fixed_traceback__ = traceback
            return instance

    ProxyException.__name__ = cls.__name__

    return ProxyException
1116121
def buildURL(self, action, **query):
        """"""
        base = urlparse.urljoin(self.server.base_url, action)
        return appendArgs(base, query)
1144213
def base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs):
        

        url = "spaces/{0}".format(
            space_id)

        if environment_id is not None:
            url = url = "{0}/environments/{1}".format(url, environment_id)

        url = "{0}/{1}".format(
            url,
            base_path_for(klass.__name__)
        )

        if resource_id:
            url = "{0}/{1}".format(url, resource_id)

        return url
1210622
def as_view(cls, endpoint, protocol, *init_args, **init_kwargs):
        '''
        
        '''
        def _wrapper(request, *args, **kwargs):
            ''' Make a new instance of the resource class and returns a coroutine for execution'''
            instance = cls(*init_args, endpoint=endpoint, request=request, **init_kwargs)
            if protocol == Resource.Protocol.http:
                return instance._wrap_http(cls.dispatch, endpoint=endpoint, *args, **kwargs)
            elif protocol == Resource.Protocol.websocket:
                return instance._wrap_ws(cls.dispatch, endpoint=endpoint, *args, **kwargs)
            elif protocol == Resource.Protocol.amqp:
                return instance._wrap_amqp(endpoint, *args, **kwargs)
            else:
                raise Exception('Communication protocol not specified')

        return _wrapper
518207
def base_url(klass, space_id, resource_id=None, public=False, environment_id=None, **kwargs):
        

        if public:
            environment_slug = ""
            if environment_id is not None:
                environment_slug = "/environments/{0}".format(environment_id)
            return "spaces/{0}{1}/public/content_types".format(space_id, environment_slug)
        return super(ContentType, klass).base_url(
            space_id,
            resource_id=resource_id,
            environment_id=environment_id,
            **kwargs
        )
682282
def generate_url(self, name: str, **kwargs) -> str:
        
        return self.urlmapper.generate(name, **kwargs)
542808
def get_view(self):
        
        view = self.view
        if not view.is_initialized:
            view.initialize()
        if not view.proxy_is_active:
            view.activate_proxy()
        return view.proxy.widget
679876
def make_proxy_method(cls, name):
        

        i = cls()
        view = getattr(i, name)

        if cls.decorators:
            for decorator in cls.decorators:
                view = decorator(view)

        @functools.wraps(view)
        def proxy(**forgettable_view_args):
            # Always use the global request object's view_args, because they
            # can be modified by intervening function before an endpoint or
            # wrapper gets called. This matches Flask's behavior.
            del forgettable_view_args

            if hasattr(i, "before_request"):
                response = i.before_request(name, **request.view_args)
                if response is not None:
                    return response

            before_view_name = "before_" + name
            if hasattr(i, before_view_name):
                before_view = getattr(i, before_view_name)
                response = before_view(**request.view_args)
                if response is not None:
                    return response

            response = view(**request.view_args)

            # You can also return a dict or None, it will pass it to render
            if isinstance(response, dict) or response is None:
                response = response or {}
                if hasattr(i, "_renderer"):
                    response = i._renderer(response)
                else:
                    df_v_t = "%s/%s.html" % (cls.__name__, view.__name__)
                    response.setdefault("template_", df_v_t)
                    response = i.render_(**response)

            if not isinstance(response, Response):
                response = make_response(response)

            after_view_name = "after_" + name
            if hasattr(i, after_view_name):
                after_view = getattr(i, after_view_name)
                response = after_view(response)

            if hasattr(i, "after_request"):
                response = i.after_request(name, response)

            return response

        return proxy
1021444
def URL(base, path, segments=None, defaults=None):
    
    # Make a copy of the Segments class
    url_class = type(Segments.__name__, Segments.__bases__,
                     dict(Segments.__dict__))
    segments = [] if segments is None else segments
    defaults = [] if defaults is None else defaults
    # For each segment attach a property capable of getting and setting it
    for segment in segments:
        setattr(url_class, segment, url_class._segment(segment))
    # Instantiate the class with the actual parameters
    return url_class(base, path, segments, defaults)
138645
def get_api_root_view(self, api_urls=None):
        
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        class APIRootView(views.APIView):
            _ignore_model_permissions = True
            exclude_from_schema = True

            def get(self, request, *args, **kwargs):
                # Return a plain {"name": "hyperlink"} response.
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in sorted(api_root_dict.items(), key=itemgetter(0)):
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                return Response(ret)

        return APIRootView.as_view()
1210019
def get_proxy_ancestor_classes(klass):
    
    proxy_ancestor_classes = set()
    for superclass in klass.__bases__:
        if hasattr(superclass, '_meta') and superclass._meta.proxy:
            proxy_ancestor_classes.add(superclass)
        proxy_ancestor_classes.update(
            get_proxy_ancestor_classes(superclass))
    return proxy_ancestor_classes
47547
def base_url(self) -> _URL:
        """"""

        # Support for <base> tag.
        base = self.find('base', first=True)
        if base:
            result = base.attrs.get('href', '').strip()
            if result:
                return result

        # Parse the url to separate out the path
        parsed = urlparse(self.url)._asdict()

        # Remove any part of the path after the last '/'
        parsed['path'] = '/'.join(parsed['path'].split('/')[:-1]) + '/'

        # Reconstruct the url with the modified path
        parsed = (v for v in parsed.values())
        url = urlunparse(parsed)

        return url
63895
def _proxy(self, url, urlparams=None):
        
        for k,v in request.params.iteritems():
            urlparams[k]=v
        query = urlencode(urlparams)
        full_url = url
        if query:
            if not full_url.endswith("?"):
                full_url += "?"
            full_url += query

        # build the request with its headers
        req = urllib2.Request(url=full_url)
        for header in request.headers:
            if header.lower() == "host":
                req.add_header(header, urlparse.urlparse(url)[1])
            else:
                req.add_header(header, request.headers[header])
        res = urllib2.urlopen(req)

        # add response headers
        i = res.info()
        response.status = res.code
        got_content_length = False
        for header in i:
            # We don't support serving the result as chunked
            if header.lower() == "transfer-encoding":
                continue
            if header.lower() == "content-length":
                got_content_length = True
            response.headers[header] = i[header]

        # return the result
        result = res.read()
        res.close()

        #if not got_content_length:
        #    response.headers['content-length'] = str(len(result))
        return result
89987
def root(self, request, url):
        
        # Delegate to the appropriate method, based on the URL.
        if url is None:
            return self.main_view(request)
        try:
            plugin_name, rest_of_url = url.split('/', 1)
        except ValueError:  # need more than 1 value to unpack
            plugin_name, rest_of_url = url, None
        try:
            plugin = self.plugins[plugin_name]
        except KeyError:
            raise http.Http404('A plugin with the requested name '
                               'does not exist.')
        return plugin.model_view(request, self, rest_of_url)
634006
def set_base_url(url):
    
    global _base_url, _dirty

    LOGGER.debug('Setting base URL to %s', url)
    _base_url = url
    _dirty = True
91696
def view(self):
        
        proxied = get_proxied_expr(self)
        kv = dict((attr, getattr(proxied, attr)) for attr in get_attrs(proxied))
        return type(proxied)(**kv)