def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then a Rackspace Cloud File URL is 
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when 
    `FlaskRSF.init_app` is invoked, this function replaces `flask.url_for` in 
    templates automatically. It is unlikely that this function will 
    need to be directly called from within your application code, unless you 
    need to refer to static assets outside of your templates.
    """
    app = current_app
    if "RSF_CONTAINER_NAME" not in app.config:
        raise ValueError("RSF_CONTAINER_NAME not found in app configuration.")

    if app.debug and not app.config["USE_RSF_DEBUG"]:
        return flask_url_for(endpoint, **values)

    if endpoint == "static" or endpoint.endswith(".static"):
        pyrax.set_credentials(["RSF_USERNAME"], ["RSF_API_KEY"])
        cf = pyrax.cloudfiles
        cont = cf.create_container(app.config["RSF_CONTAINER_NAME"])
        scheme = "http"
        bucket_path = cont.cdn_uri
        if app.config["RSF_USE_HTTPS"]:
            scheme = "https"
            bucket_path = cont.cdn_ssl_uri
        bucket_path = re.sub(r"(http[s]*://)", r"", bucket_path)
        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #2
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is 
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when 
    `FlaskS3.init_app` is invoked, this function replaces 
    `flask.url_for` in templates automatically. It is unlikely that this
    function will need to be directly called from within your 
    application code, unless you need to refer to static assets outside 
    of your templates.
    """
    app = current_app
    if 'S3_BUCKET_NAME' not in app.config:
        raise ValueError("S3_BUCKET_NAME not found in app configuration.")

    if app.debug and not app.config['USE_S3_DEBUG']:
        return flask_url_for(endpoint, **values)

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'http'
        if app.config['S3_USE_HTTPS']:
            scheme = 'https'
        bucket_path = '%s.%s' % (app.config['S3_BUCKET_NAME'],
                                 app.config['S3_BUCKET_DOMAIN'])
        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #3
0
def url_for(endpoint, **values):
    if redirect_url_prefix is None:
        return flask_url_for(endpoint, **values)
    else:
        if '_external' in values:
            del values['_external']
        return redirect_url_prefix + flask_url_for(endpoint, **values)
Beispiel #4
0
    def static_url_for(self, endpoint, **values):
        """
        This function uses Flask's url_for under the hood and accepts the
        same arguments. The only differences are it will prefix a host URL if
        one exists and if a manifest is available it will look up the filename
        from the manifest.

        :param endpoint: The endpoint of the URL
        :type endpoint: str
        :param values: Arguments of the URL rule
        :return: Static file path.
        """
        if not self.has_manifest:
            if self.host_url:
                return self._prepend_host_url(self.host_url,
                                              values.get("filename"))
            else:
                return flask_url_for(endpoint, **values)

        new_filename = {}
        filename = values.get("filename")

        if filename:
            # If the manifest lookup fails then use the original filename
            # so that Flask doesn't throw a 500, but instead a proper 404.
            # The above only happens if your template has an invalid filename.
            new_filename["filename"] = self.manifest.get(filename, filename)

        merged_values = {**values, **new_filename}

        if self.host_url:
            return self._prepend_host_url(self.host_url,
                                          merged_values.get("filename"))
        else:
            return flask_url_for(endpoint, **merged_values)
def url_for(endpoint, **values):
    app = current_app
    if app.config.get('TESTING', False):
        return flask_url_for(endpoint, **values)
    if 'AZURE_STORAGE_CONTAINER_NAME' not in app.config:
        raise ValueError(
            "AZURE_STORAGE_CONTAINER_NAME not found in app configuration.")

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'https'
        if not app.config.get("AZURE_STORAGE_USE_HTTPS", True):
            scheme = 'http'
        # allow per url override for scheme
        scheme = values.pop('_scheme', scheme)
        # manage other special values, all have no meaning for static urls
        values.pop('_external', False)  # external has no meaning here
        values.pop('_anchor', None)  # anchor as well
        values.pop('_method', None)  # method too

        url_format = '%(container_domain)s/%(container_name)s/%(virtual_folder)s'

        bucket_path = url_format % {
            'container_domain': app.config['AZURE_STORAGE_DOMAIN'],
            'container_name': app.config['AZURE_STORAGE_CONTAINER_NAME'],
            'virtual_folder': app.config['AZURE_STORAGE_VIRTUAL_FOLDER_NAME']
        }
        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #6
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `FlaskS3.init_app` is invoked, this function replaces
    `flask.url_for` in templates automatically. It is unlikely that this
    function will need to be directly called from within your
    application code, unless you need to refer to static assets outside
    of your templates.
    """
    app = current_app
    if app.config.get('TESTING', False) and not app.config.get('FLASKS3_OVERRIDE_TESTING', True):
        return flask_url_for(endpoint, **values)
    if 'FLASKS3_BUCKET_NAME' not in app.config:
        raise ValueError("FLASKS3_BUCKET_NAME not found in app configuration.")

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'https'
        if not app.config.get("FLASKS3_USE_HTTPS", True):
            scheme = 'http'

        # allow per url override for scheme
        scheme = values.pop('_scheme', scheme)

        bucket_path, values = _get_bucket_name(**values)

        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        built = urls.build(endpoint, values=values, force_external=True)
        return built
    return flask_url_for(endpoint, **values)
Beispiel #7
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is 
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when 
    `FlaskS3.init_app` is invoked, this function replaces `flask.url_for` in 
    templates automatically. It is unlikely that this function will 
    need to be directly called from within your application code, unless you 
    need to refer to static assets outside of your templates.
    """
    app = current_app
    if 'S3_BUCKET_NAME' not in app.config:
        raise ValueError("S3_BUCKET_NAME not found in app configuration.")
    
    if app.debug and not app.config['USE_S3_DEBUG']:
        return flask_url_for(endpoint, **values)
    
    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'http'
        if app.config['S3_USE_HTTPS']:
            scheme = 'https'
        bucket_path = '%s.%s' % (app.config['S3_BUCKET_NAME'], 
                                 app.config['S3_BUCKET_DOMAIN'])
        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #8
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then a URL to the CDN is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `CDN.init_app` is invoked, this function replaces `flask.url_for` in
    templates automatically. It is unlikely that this function will need to be
    directly called from within your application code, unless you need to refer
    to static assets outside of your templates.
    """
    app = current_app

    if app.config['CDN_DEBUG'] or _request_ctx_stack.top is None:
        return flask_url_for(endpoint, **values)

    def endpoint_match(endpoint):
        if endpoint in app.config['CDN_ENDPOINTS']:
            return True

        for x in app.config['CDN_ENDPOINTS']:
            if endpoint.endswith('.%s' % x):
                return True

        return False

    if endpoint_match(endpoint):
        try:
            scheme = values.pop('_scheme')
        except KeyError:
            scheme = 'http'
            cdn_https = app.config['CDN_HTTPS']
            if cdn_https is True or (cdn_https is None and request.is_secure):
                scheme = 'https'

        static_folder = app.static_folder
        if (request.blueprint is not None
                and request.blueprint in app.blueprints
                and app.blueprints[request.blueprint].has_static_folder):
            static_folder = app.blueprints[request.blueprint].static_folder

        elif '.' in endpoint:
            blueprint_name = endpoint.split('.')[0]
            if blueprint_name in app.blueprints and app.blueprints[
                    blueprint_name].has_static_folder:
                static_folder = app.blueprints[blueprint_name].static_folder

        urls = app.url_map.bind(app.config['CDN_DOMAIN'], url_scheme=scheme)

        if app.config['CDN_TIMESTAMP']:
            path = os.path.join(static_folder, values['filename'])
            values['t'] = int(os.path.getmtime(path))

        values['v'] = app.config['CDN_VERSION']

        return urls.build(endpoint, values=values, force_external=True)

    return flask_url_for(endpoint, **values)
Beispiel #9
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `FlaskS3.init_app` is invoked, this function replaces
    `flask.url_for` in templates automatically. It is unlikely that this
    function will need to be directly called from within your
    application code, unless you need to refer to static assets outside
    of your templates.
    """
    app = current_app
    if app.config.get('TESTING', False) and not app.config.get('FLASKS3_OVERRIDE_TESTING', True):
        return flask_url_for(endpoint, **values)
    if 'FLASKS3_BUCKET_NAME' not in app.config:
        raise ValueError("FLASKS3_BUCKET_NAME not found in app configuration.")

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'https'
        if not app.config.get("FLASKS3_USE_HTTPS", True):
            scheme = 'http'
        # allow per url override for scheme
        scheme = values.pop('_scheme', scheme)
        # manage other special values, all have no meaning for static urls
        values.pop('_external', False)  # external has no meaning here
        values.pop('_anchor', None)  # anchor as well
        values.pop('_method', None)  # method too

        if app.config['FLASKS3_URL_STYLE'] == 'host':
            url_format = '%(bucket_name)s.%(bucket_domain)s'
        elif app.config['FLASKS3_URL_STYLE'] == 'path':
            url_format = '%(bucket_domain)s/%(bucket_name)s'
        else:
            raise ValueError('Invalid S3 URL style: "%s"'
                             % app.config['FLASKS3_URL_STYLE'])

        bucket_path = url_format % {
            'bucket_name': app.config['FLASKS3_BUCKET_NAME'],
            'bucket_domain': app.config['FLASKS3_BUCKET_DOMAIN'],
        }

        if app.config['FLASKS3_CDN_DOMAIN']:
            bucket_path = '%s' % app.config['FLASKS3_CDN_DOMAIN']

        # Both S3 and CDN urls should use the prefix if it exists
        bucket_path += _get_statics_prefix(app).rstrip('/')

        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #10
0
def url_for(endpoint, **values):
    if "_domain" in values:
        domain = values["_domain"]
        del values["_domain"]
    else:
        domain = _MultidomainBlueprint__endpoint_domain.get(endpoint, None)

    if domain and domain != g.domain:
        values["_external"] = False  # Remove external parameter for flask
        return "http://" + domain + DOMAIN_SUFFIX + flask_url_for(endpoint, **values)

    return flask_url_for(endpoint, **values)
Beispiel #11
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `FlaskS3.init_app` is invoked, this function replaces
    `flask.url_for` in templates automatically. It is unlikely that this
    function will need to be directly called from within your
    application code, unless you need to refer to static assets outside
    of your templates.
    """
    app = current_app
    if app.config.get('TESTING', False) and not app.config.get('FLASKS3_OVERRIDE_TESTING', True):
        return flask_url_for(endpoint, **values)
    if 'FLASKS3_BUCKET_NAME' not in app.config:
        raise ValueError("FLASKS3_BUCKET_NAME not found in app configuration.")

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'https'
        if not app.config.get("FLASKS3_USE_HTTPS", True):
            scheme = 'http'
        # allow per url override for scheme
        scheme = values.pop('_scheme', scheme)
        # manage other special values, all have no meaning for static urls
        values.pop('_external', False)  # external has no meaning here
        values.pop('_anchor', None)  # anchor as well
        values.pop('_method', None)  # method too

        if app.config['FLASKS3_URL_STYLE'] == 'host':
            url_format = '%(bucket_name)s.%(bucket_domain)s'
        elif app.config['FLASKS3_URL_STYLE'] == 'path':
            url_format = '%(bucket_domain)s/%(bucket_name)s'
        else:
            raise ValueError('Invalid S3 URL style: "%s"'
                             % app.config['FLASKS3_URL_STYLE'])

        bucket_path = url_format % {
            'bucket_name': app.config['FLASKS3_BUCKET_NAME'],
            'bucket_domain': app.config['FLASKS3_BUCKET_DOMAIN'],
        }

        if app.config['FLASKS3_CDN_DOMAIN']:
            bucket_path = '%s' % app.config['FLASKS3_CDN_DOMAIN']

        # Both S3 and CDN urls should use the prefix if it exists
        bucket_path += _get_statics_prefix(app).rstrip('/')

        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #12
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then a URL to the CDN is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `CDN.init_app` is invoked, this function replaces `flask.url_for` in
    templates automatically. It is unlikely that this function will need to be
    directly called from within your application code, unless you need to refer
    to static assets outside of your templates.
    """
    app = current_app

    if app.config['CDN_DEBUG']:
        return flask_url_for(endpoint, **values)

    def endpoint_match(endpoint):
        if endpoint in app.config['CDN_ENDPOINTS']:
            return True

        for x in app.config['CDN_ENDPOINTS']:
            if endpoint.endswith('.%s' % x):
                return True

        return False

    if endpoint_match(endpoint):
        try:
            scheme = values.pop('_scheme')
        except KeyError:
            scheme = 'http'
            cdn_https = app.config['CDN_HTTPS']
            if cdn_https is True or (cdn_https is None and request.is_secure):
                scheme = 'https'

        static_folder = app.static_folder
        if (request.blueprint is not None and
                app.blueprints[request.blueprint].has_static_folder):
            static_folder = app.blueprints[request.blueprint].static_folder

        urls = app.url_map.bind(app.config['CDN_DOMAIN'], url_scheme=scheme)

        if app.config['CDN_TIMESTAMP']:
            path = os.path.join(static_folder, values['filename'])
            values['t'] = int(os.path.getmtime(path))

        return urls.build(endpoint, values=values, force_external=True)

    return flask_url_for(endpoint, **values)
Beispiel #13
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then a URL to the CDN is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `CDN.init_app` is invoked, this function replaces `flask.url_for` in
    templates automatically. It is unlikely that this function will need to be
    directly called from within your application code, unless you need to refer
    to static assets outside of your templates.
    """
    app = current_app

    if app.debug:
        return flask_url_for(endpoint, **values)

    if endpoint == 'static' or endpoint.endswith('.static'):
        cdn_https = app.config['CDN_HTTPS']

        scheme = 'http'
        if cdn_https is True or (cdn_https is None and request.is_secure):
            scheme = 'https'

        static_folder = app.static_folder
        if request.blueprint is not None:
            static_folder = app.blueprints[request.blueprint].static_folder

        domain = app.config['CDN_DOMAIN']

        if app.config['CDN_FOLDER'] is not None:
            domain = domain + "/"
            domain = domain + str(app.config['CDN_FOLDER'])

        if app.config['CDN_VERSION'] is not None:
            domain = domain + "/"
            domain = domain + str(app.config['CDN_VERSION'])

        urls = app.url_map.bind(domain, url_scheme=scheme)

        if app.config['CDN_TIMESTAMP']:
            path = os.path.join(static_folder, values['filename'])
            values['t'] = int(os.path.getmtime(path))

        return urls.build(endpoint, values=values, force_external=True)

    return flask_url_for(endpoint, **values)
Beispiel #14
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then a URL to the CDN is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `CDN.init_app` is invoked, this function replaces `flask.url_for` in
    templates automatically. It is unlikely that this function will need to be
    directly called from within your application code, unless you need to refer
    to static assets outside of your templates.
    """
    app = current_app

    if app.debug:
        return flask_url_for(endpoint, **values)

    if endpoint == 'static' or endpoint.endswith('.static'):
        cdn_https = app.config['CDN_HTTPS']

        scheme = 'http'
        if cdn_https is True or (cdn_https is None and request.is_secure):
            scheme = 'https'

        static_folder = app.static_folder
        if request.blueprint is not None:
            static_folder = app.blueprints[request.blueprint].static_folder

        domain = app.config['CDN_DOMAIN']

        if app.config['CDN_FOLDER'] is not None:
            domain = domain + "/"
            domain = domain + str(app.config['CDN_FOLDER'])

        if app.config['CDN_VERSION'] is not None:
            domain = domain + "/"
            domain = domain + str(app.config['CDN_VERSION'])

        urls = app.url_map.bind(domain, url_scheme=scheme)

        if app.config['CDN_TIMESTAMP']:
            path = os.path.join(static_folder, values['filename'])
            values['t'] = int(os.path.getmtime(path))

        return urls.build(endpoint, values=values, force_external=True)

    return flask_url_for(endpoint, **values)
Beispiel #15
0
def url_for(*args, **kwargs):
    """ `flask.url_for`는 flask 앱의 context가 필요합니다. 따라서 context안에서
    생성한 url을 가져와서 사용하면됩니다. 테스트 코드 내부에서 그냥
    `flask.url_for`를 사용하면 에러가 나게됩니다.
    """
    with app.test_request_context() as ctx_:
        return flask_url_for(*args, **kwargs)
Beispiel #16
0
    def url_for(self, model, **kw):
        """Returns the URL for the specified model, similar to
        :func:`flask.url_for`.

        `model` is a SQLAlchemy model class. This must be a model on
        which :meth:`create_api_blueprint` has been invoked previously,
        otherwise a :exc:`KeyError` is raised.

        This method only returns URLs for endpoints created by this
        :class:`APIManager`.

        The remaining keyword arguments are passed directly on to
        :func:`flask.url_for`.

        .. _Flask request context: http://flask.pocoo.org/docs/0.10/reqcontext/

        """
        collection_name = self.created_apis_for[model].collection_name
        blueprint_name = self.created_apis_for[model].blueprint_name
        api_name = APIManager.api_name(collection_name)
        parts = [blueprint_name, api_name]
        # If we are looking for a relationship URL, the view name ends with
        # '.relationships'.
        if 'relationship' in kw and kw.pop('relationship'):
            parts.append('relationships')
        url = flask_url_for('.'.join(parts), **kw)
        # if _absolute_url:
        #     url = urljoin(request.url_root, url)
        return url
Beispiel #17
0
 def url_for(self, endpoint, **kwargs):
     """
     A small helper to generate a URL to the given endpoint in the context of `self.app_context`.
     """
     with app.app_context():
         url = flask_url_for(endpoint, **kwargs)
         return self.get_server_url() + url
Beispiel #18
0
 def url_for(self, endpoint, **kwargs):
     """
     A small helper to generate a URL to the given endpoint in the context of `self.app_context`.
     """
     with self.app_context:
         url = flask_url_for(endpoint, **kwargs)
         return url
Beispiel #19
0
def url_for(endpoint, **values):
    if endpoint == 'admin.static':
        filename = values.pop('filename')
        query = url_encode(values)
        url_prefix = current_app.config['ADMIN_STATIC_URL']
        return '{}?{}'.format(url_join(url_prefix, filename), query)
    return flask_url_for(endpoint, **values)
Beispiel #20
0
    def url_for(self, model, **kw):
        """Returns the URL for the specified model, similar to
        :func:`flask.url_for`.

        `model` is a SQLAlchemy model class. This must be a model on
        which :meth:`create_api_blueprint` has been invoked previously,
        otherwise a :exc:`KeyError` is raised.

        This method only returns URLs for endpoints created by this
        :class:`APIManager`.

        The remaining keyword arguments are passed directly on to
        :func:`flask.url_for`.

        .. _Flask request context: http://flask.pocoo.org/docs/0.10/reqcontext/

        """
        collection_name = self.created_apis_for[model].collection_name
        blueprint_name = self.created_apis_for[model].blueprint_name
        api_name = APIManager.api_name(collection_name)
        parts = [blueprint_name, api_name]
        # If we are looking for a relationship URL, the view name ends with
        # '.relationships'.
        if 'relationship' in kw and kw.pop('relationship'):
            parts.append('relationships')
        url = flask_url_for('.'.join(parts), **kw)
        # if _absolute_url:
        #     url = urljoin(request.url_root, url)
        return url
Beispiel #21
0
def url_for(*args, **kwargs) -> str:
    host = get_host()
    redirect_url = urlparse(flask_url_for(*args, **kwargs))
    # noinspection PyProtectedMember
    return redirect_url._replace(
        netloc=host,
        scheme="https" if getenv("ENV") == "prod" else "http").geturl()
Beispiel #22
0
def url_for(endpoint, **values):
    if endpoint == 'admin.static':
        filename = values.pop('filename')
        query = url_encode(values)
        url_prefix = current_app.config['ADMIN_STATIC_URL']
        return '{}?{}'.format(url_join(url_prefix, filename), query)
    return flask_url_for(endpoint, **values)
Beispiel #23
0
def url_for(*a, **kw):
    """Generate external URLs with HTTPS (if configured)."""
    try:
        kw['_external'] = False
        path = flask_url_for(*a, **kw)
        return urljoin(get_app_url(), path)
    except RuntimeError:
        return None
Beispiel #24
0
def url_for(endpoint, **kwargs):
    if os.getenv('SANDSTORM'):
        kwargs.setdefault('_external', True)
        if request.headers.get('X-Forwarded-Proto') == "https":
            kwargs.setdefault('_scheme', 'https')
        else:
            kwargs.setdefault('_scheme', 'http')
    return flask_url_for(endpoint, **kwargs)
Beispiel #25
0
    def url_for(*args, **kwargs):
        """Generate url using flask.url_for and the current app ctx.

        This is necessary as we don't want to share the same application
        context across requests.
        """
        with app.app_context():
            return flask_url_for(*args, **kwargs)
Beispiel #26
0
    def url_for(*args, **kwargs):
        """Generate url using flask.url_for and the current app ctx.

        This is necessary as we don't want to share the same application
        context across requests.
        """
        with app.app_context():
            return flask_url_for(*args, **kwargs)
Beispiel #27
0
def url_for(endpoint, **kwargs):
	# Persist the lens parameter across navigations.
	lens = request.args.get('lens')
	if report_util.is_valid_lens(lens):
		kwargs['lens'] = lens

	# Pass through to the built-in method.
	return flask_url_for(endpoint, **kwargs)
Beispiel #28
0
def url_for(endpoint, **kwargs):
    if os.getenv("SANDSTORM"):
        kwargs.setdefault("_external", True)
        if request.headers.get("X-Forwarded-Proto") == "https":
            kwargs.setdefault("_scheme", "https")
        else:
            kwargs.setdefault("_scheme", "http")
    return flask_url_for(endpoint, **kwargs)
Beispiel #29
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is 
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when 
    `FlaskS3.init_app` is invoked, this function replaces 
    `flask.url_for` in templates automatically. It is unlikely that this
    function will need to be directly called from within your 
    application code, unless you need to refer to static assets outside 
    of your templates.
    """
    app = current_app
    if 'S3_BUCKET_NAME' not in app.config:
        raise ValueError("S3_BUCKET_NAME not found in app configuration.")

    if app.debug and not app.config['USE_S3_DEBUG']:
        return flask_url_for(endpoint, **values)

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'http'
        scheme = app.config['S3_URL_SCHEME'] or 'https'
        bucket_path = '%s.%s' % (app.config['S3_BUCKET_NAME'],
                                 app.config['S3_BUCKET_DOMAIN'])
        if app.config['S3_CDN_DOMAIN']:
            bucket_path = '%s' % app.config['S3_CDN_DOMAIN']
        if app.config['S3_PREFIX']:
            bucket_path = "/".join((bucket_path, app.config['S3_PREFIX']))
        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        try:
            mimetype = mimetypes.guess_type(values['filename'])[0]
        except KeyError:
            mimetype = None
        if app.config['USE_GZIP']:
            accept_encoding = request.headers.get('Accept-Encoding', '')
            if (mimetype in app.config['S3_GZIP_CONTENT_TYPES']
                    and 'gzip' in accept_encoding.lower()):
                values['filename'] += '.gz'
        url = urls.build(endpoint, values=values, force_external=True)
        if app.config['S3_URL_SCHEME'] is None:
            url = re.sub(r'^https://', '//', url)
        return url
    return flask_url_for(endpoint, **values)
Beispiel #30
0
def url_for(*a, **kw):
    """Generate external URLs with HTTPS (if configured)."""
    try:
        kw['_external'] = True
        if get_config('PREFERRED_URL_SCHEME'):
            kw['_scheme'] = get_config('PREFERRED_URL_SCHEME')
        return flask_url_for(*a, **kw)
    except RuntimeError:
        return None
Beispiel #31
0
def url_for(*a, **kw):
    """Overwrite Flask url_for to force external paths."""
    try:
        kw['_external'] = False
        query = kw.pop('_query', None)
        path = flask_url_for(*a, **kw)
        return url_external(path, query)
    except RuntimeError:
        return None
Beispiel #32
0
def url_for(*a, **kw):
    """ Always generate external URLs. """
    try:
        kw['_external'] = True
        if app.config.get('PREFERRED_URL_SCHEME'):
            kw['_scheme'] = app.config.get('PREFERRED_URL_SCHEME')
        return flask_url_for(*a, **kw)
    except RuntimeError:
        return None
Beispiel #33
0
def url_for(*a, **kw):
    """ Always generate external URLs. """
    try:
        kw['_external'] = True
        if current_app.config.get('PREFERRED_URL_SCHEME'):
            kw['_scheme'] = current_app.config.get('PREFERRED_URL_SCHEME')
        return flask_url_for(*a, **kw)
    except RuntimeError:
        return None
Beispiel #34
0
def url_for(*args, **kwargs):
    '''
    Override of flask url_for that correctly sets https or http based on the
    SERVER_PROTOCOL config variable.
    '''
    if kwargs.get('_external', False):
        kwargs['_scheme'] = current_app.config.get('SERVER_PROTOCOL', 'https')

    return flask_url_for(*args, **kwargs)
Beispiel #35
0
def url_for(*args, **kwargs):
    '''
    Override of flask url_for that correctly sets https or http based on the
    SERVER_PROTOCOL config variable.
    '''
    if kwargs.get('_external', False):
        kwargs['_scheme'] = current_app.config.get('SERVER_PROTOCOL', 'https')

    return flask_url_for(*args, **kwargs)
Beispiel #36
0
def url_for(*a, **kw):
    """Generate external URLs with HTTPS (if configured)."""
    try:
        kw['_external'] = True
        if get_config('PREFERRED_URL_SCHEME'):
            kw['_scheme'] = get_config('PREFERRED_URL_SCHEME')
        return flask_url_for(*a, **kw)
    except RuntimeError:
        return None
Beispiel #37
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then an Amazon S3 URL is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `FlaskS3.init_app` is invoked, this function replaces
    `flask.url_for` in templates automatically. It is unlikely that this
    function will need to be directly called from within your
    application code, unless you need to refer to static assets outside
    of your templates.
    """
    app = current_app
    if app.config.get('TESTING', False) and not app.config.get('S3_OVERRIDE_TESTING', True):
        return flask_url_for(endpoint, **values)
    if 'S3_BUCKET_NAME' not in app.config:
        raise ValueError("S3_BUCKET_NAME not found in app configuration.")

    if endpoint == 'static' or endpoint.endswith('.static'):
        scheme = 'https'
        if app.config['S3_USE_HTTP']:
            scheme = 'http'

        if app.config['S3_URL_STYLE'] == 'host':
            url_format = '%(bucket_name)s.%(bucket_domain)s'
        elif app.config['S3_URL_STYLE'] == 'path':
            url_format = '%(bucket_domain)s/%(bucket_name)s'
        else:
            raise ValueError('Invalid S3 URL style: "%s"'
                             % app.config['S3_URL_STYLE'])

        bucket_path = url_format % {
            'bucket_name': app.config['S3_BUCKET_NAME'],
            'bucket_domain': app.config['S3_BUCKET_DOMAIN'],
        }

        if app.config['S3_CDN_DOMAIN']:
            bucket_path = '%s' % app.config['S3_CDN_DOMAIN']
        urls = app.url_map.bind(bucket_path, url_scheme=scheme)
        return urls.build(endpoint, values=values, force_external=True)
    return flask_url_for(endpoint, **values)
Beispiel #38
0
def url_for(*a, **kw):
    """Overwrite Flask url_for to force external paths"""
    try:
        kw["_external"] = False
        query = kw.pop("_query", None)
        relative = kw.pop("_relative", False)
        path = flask_url_for(*a, **kw)
        return url_external(path, query, relative=relative)
    except RuntimeError:
        return None
Beispiel #39
0
def url_for(endpoint: str, **values: dict) -> Any:
    """
    Build an URL for an ``endpoint``.

    Tries Flask first, then falls back to...
    """
    try:
        return flask_url_for(endpoint, **values)
    except RuntimeError as e:
        return endpoint
Beispiel #40
0
def url_for(endpoint, **values):
    from flask import url_for as flask_url_for
    url = flask_url_for(endpoint, **values)

    external = values.pop('_external', False)
    if external:
        return url

    if endpoint == 'static':
        url = app.config['CDN_URL_PREFIX'] + url
    return url
Beispiel #41
0
def url_for_app(app, endpoint, **values):
    ref_url = url_parse(get('locations')['base_url'])
    url = flask_url_for(endpoint,
                        _scheme=ref_url.scheme,
                        _external=True,
                        **values)
    url_ = url_parse(url)
    new = url_unparse(
        (ref_url.scheme, url_.netloc, path_for_app(app, url_.path), url_.query,
         url_.fragment))
    return new
Beispiel #42
0
def url_for(endpoint, **values):
    from flask import url_for as flask_url_for
    url = flask_url_for(endpoint, **values)

    external = values.pop('_external', False)
    if external:
        return url

    if endpoint == 'static':
        url = app.config['CDN_URL_PREFIX'] + url
    return url
Beispiel #43
0
def url_for(endpoint, **values):
    app = current_app
    
    if endpoint == 'static' or endpoint.endswith('.static'):
        bucket_path = "{}/{}".format(app.config['S3_BUCKET_DOMAIN'], app.config['S3_BUCKET'])
        
        urls = app.url_map.bind(bucket_path)
        built_url = urls.build(endpoint, values=values, force_external=True)
        
        scheme, netloc, path, params, query, fragment = urlparse(built_url)
        return urlunparse(("", netloc, path, params, query, fragment))
    return flask_url_for(endpoint, **values)
Beispiel #44
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint.

    If the endpoint is for a static resource then a URL to the CDN is
    generated, otherwise the call is passed on to `flask.url_for`.

    Because this function is set as a jinja environment variable when
    `CDN.init_app` is invoked, this function replaces `flask.url_for` in
    templates automatically. It is unlikely that this function will need to be
    directly called from within your application code, unless you need to refer
    to static assets outside of your templates.
    """
    app = current_app

    if app.debug and not app.config["CDN_DEBUG"]:
        return flask_url_for(endpoint, **values)

    if endpoint == "static" or endpoint.endswith(".static"):
        cdn_https = app.config["CDN_HTTPS"]

        scheme = "http"
        if cdn_https is True or (cdn_https is None and request.is_secure):
            scheme = "https"

        static_folder = app.static_folder
        if request.blueprint is not None and app.blueprints[request.blueprint].static_folder:
            static_folder = app.blueprints[request.blueprint].static_folder

        cdn_domain = app.config["CDN_DOMAIN"]
        urls = app.url_map.bind(cdn_domain, url_scheme=scheme)

        if app.config["CDN_TIMESTAMP"]:
            path = os.path.join(static_folder, values["filename"])
            values["t"] = int(os.path.getmtime(path))

        url = urls.build(endpoint, values=values, force_external=True)
        return url.replace(cdn_domain.lower(), cdn_domain)

    return flask_url_for(endpoint, **values)
Beispiel #45
0
def url_for(endpoint, **values):
    appctx = _app_ctx_stack.top
    if appctx is None:
        raise RuntimeError('Attempted to generate a URL without the '
                           'application context being pushed. This has to be '
                           'executed when application context is available.')
    app = appctx.app

    file_name = values.get('filename')
    force_no_cdn = values.pop('_force_no_cdn', False)

    if app.config['CDN_DEBUG'] or force_no_cdn or not file_name:
        return flask_url_for(endpoint, **values)

    values['_external'] = True

    url = flask_url_for(endpoint, **values)

    pr = urlparse(url)
    query = dict(parse_qsl(pr.query))

    if app.config['CDN_VERSION']:
        query.update({'v': app.config['CDN_VERSION']})
    if app.config['CDN_TIMESTAMP'] and file_name:
        path = None
        if (request.blueprint is not None
                and app.blueprints[request.blueprint].has_static_folder):
            static_files = app.blueprints[request.blueprint].static_folder
            path = os.path.join(static_files, file_name)
        if path is None or not os.path.exists(path):
            path = os.path.join(app.static_folder, file_name)
        query.update({'t': int(os.path.getmtime(path))})

    pr_list = list(pr)
    if app.config['CDN_HTTPS'] is True:
        pr_list[0] = 'https'
    pr_list[1] = app.config['CDN_DOMAIN']
    pr_list[4] = urlencode(query)
    return urlunparse(pr_list)
Beispiel #46
0
def _url_for(endpoint: str, **values) -> Union[str, None]:
    """
    The same as flask's url_for, except this also supports building external
    urls for hosts that are different from app.config.SERVER_NAME. One case
    where this is especially useful is for single page apps, where the frontend
    is not hosted by the same server as the backend, but the backend still needs
    to generate urls to frontend routes

    :param endpoint: the name of the endpoint
    :param values: the variable arguments of the URL rule
    :return: a url path, or None
    """
    _external_host = values.pop('_external_host', None)
    is_external = bool(_external_host or values.get('_external'))
    external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME')
    if not is_external or not external_host:
        return flask_url_for(endpoint, **values)

    if '://' not in external_host:
        external_host = f'http://{external_host}'
    values.pop('_external')
    return external_host.rstrip('/') + flask_url_for(endpoint, **values)
Beispiel #47
0
def url_for(endpoint, **values):
    """
    Generates a URL to the given endpoint with the method provided
        :param endpoint: the endpoint of the URL (name of the function)
        :param values: the variable arguments of the URL rule
        :param _params: if provided this dictionary is used to add additional parameters at runtime
    """
    runtime_parameters = values.pop('_params', None)
    if runtime_parameters:
        for k, v in runtime_parameters.items():
            # Make sure we don't overwrite compile time arguments
            if not k in values.keys():
                values[k] = v
    return flask_url_for(endpoint, **values)
Beispiel #48
0
def url_for(*a, **kw):
    """Overwrite Flask url_for to force external paths."""
    try:
        kw['_external'] = False
        query = kw.pop('_query', None)
        authorize = kw.pop('_authorize', False)
        path = flask_url_for(*a, **kw)
        if authorize is True:
            token = request.authz.to_token(scope=path)
            query = list(ensure_list(query))
            query.append(('api_key', token))
        return url_external(path, query)
    except RuntimeError:
        return None
    def static_url_for(self, endpoint, **values):
        """
        This function uses Flask's url_for under the hood and accepts the
        same arguments. The only difference is when a manifest is available
        it will look up the filename from the manifest.

        :param endpoint: The endpoint of the URL
        :type endpoint: str
        :param values: Arguments of the URL rule
        :return: Static file path.
        """
        if not self.has_manifest:
            return flask_url_for(endpoint, **values)

        new_filename = {}
        filename = values.get("filename")

        if filename:
            new_filename["filename"] = self.manifest.get(filename)

        merged_values = {**values, **new_filename}

        return flask_url_for(endpoint, **merged_values)
Beispiel #50
0
def url_for(*a, **kw):
    """Overwrite Flask url_for to force external paths."""
    try:
        kw['_external'] = False
        query = kw.pop('_query', None)
        authorize = kw.pop('_authorize', False)
        relative = kw.pop('_relative', False)
        path = flask_url_for(*a, **kw)
        if authorize is True and hasattr(request, 'authz'):
            token = request.authz.to_token(scope=path)
            query = list(ensure_list(query))
            query.append(('api_key', token))
        return url_external(path, query, relative=relative)
    except RuntimeError:
        return None
def url_for(endpoint, **values):
    if endpoint == 'static':
        state = get_state()

        try:
            rev_file = state.manifest_contents[values['filename']]
        except KeyError:
            pass
        else:
            values['filename'] = rev_file

            if state.serve_root:
                endpoint = state.endpoint
            else:
                # TODO: Handle external domains
                values['_external'] = True

    return flask_url_for(endpoint, **values)
Beispiel #52
0
def url_for(obj, **kw):
  """
  Polymorphic variant of Flask's `url_for` function.

  Behaves like the original function when the first argument is a string.
  When it's an object, it

  """
  if isinstance(obj, basestring):
    return flask_url_for(obj, **kw)

  try:
    return current_app.default_view.url_for(obj, **kw)
  except KeyError:
    if hasattr(obj, "_url"):
      return obj._url
    elif hasattr(obj, "url"):
      return obj.url

  raise BuildError(repr(obj), kw, 'GET')
Beispiel #53
0
def url_for(endpoint, **values):
    # check for language change order
    target_lang = values.pop("_lang", g.lang)

    # absolute URL?
    external = values.pop("_external", False)

    # force schema change?
    schema = values.pop("_secure", None)

    # allows to use "." for current path
    if endpoint==".":
        endpoint = request.endpoint
        path = request.script_root + urllib2.quote(request.path.encode('utf-8'))
        query_string = request.url
        if u"?" in query_string:
            try:
                if not isinstance(query_string, unicode):
                    query_string = query_string.decode("utf-8")
                path += query_string[query_string.find(u"?"):]
            except:
                pass
    else:
        path = flask_url_for(endpoint, **values)

    # check for domain change order
    target_domain = values.pop("_domain", _MultidomainBlueprint__endpoint_domain.get(endpoint, None)) or g.domain

    # if must change anything overrides this method
    if external or not schema is None or (target_domain and target_domain != g.domain) or (target_lang and target_lang!=g.lang):
        # Use https if forced or is current schema
        schema = "https://" if schema or (schema is None and g.secure_request) else "http://"

        if target_lang and target_domain in g.translate_domains and target_lang!=g.langs[0]:
            return schema + target_lang + "." + target_domain + get_domain_suffix() + path
        else:
            return schema + target_domain + get_domain_suffix() + path

    return path
Beispiel #54
0
 def inaccessible_callback(self, name, **kwargs):
     return redirect(flask_url_for('account.login', next_url=request.url))
Beispiel #55
0
def url_for(endpoint):
	if type(request.view_args) == type({}) and 'path' in request.view_args:
		return '/%s%s' % (request.view_args['path'], flask_url_for(endpoint))
	return flask_url_for(endpoint)
Beispiel #56
0
def url_for(endpoint, **kwargs):
    kwargs['_external'] = True
    return flask_url_for(endpoint, **kwargs)
def url_for(endpoint, **kwargs):
    kwargs.setdefault('_external', True)
    return flask_url_for(endpoint, **kwargs)
Beispiel #58
0
def network_path_url_for(endpoint):
	try:
		url = '/%s%s' % (request.source['network']['url_path'], flask_url_for(endpoint))
	except:
		url = flask_url_for(endpoint)
	return url
Beispiel #59
0
def url_for(admin_ui_host, method_name):
    return admin_ui_host + flask_url_for(method_name)