Return the URL of a static file, with handling of offline mode.

    Usage: ``{%  %}``
347921
def static_cdn_tag(path, cdn, cdn_only=False):
    
    clean_path = path.lstrip("/")
    if getattr(settings, "OFFLINE", False):
        return static_url(join("vendor", clean_path))
    elif cdn_only:
        return cdn
    return urljoin(cdn, clean_path)
83603
def do_GET(self):
        

        if self.path == "/":
            self.path = "/index.html"

        # Serve a file (image, css, html, etc)
        if '.' in self.path:
            extension = self.path.split('.')[-1]
            mt = self.mimetype.get(extension)

            if mt:
                filename = os.curdir + os.sep + self.path

                # Open the static file requested and send it
                if os.path.exists(filename):
                    self.send_response(200)
                    self.send_header('Content-type', mt)
                    self.end_headers()

                    if extension in ('gif', 'ico', 'jpg', 'png'):
                        # Open in binary mode, do not encode
                        with open(filename, mode='rb') as fh:
                            self.wfile.write(fh.read())
                    else:
                        # Open as plain text and encode
                        with open(filename, mode='r') as fh:
                            self.wfile.write(fh.read().encode())
                else:
                    log.error("404: %s not found" % self.path)
                    self.send_error(404, 'File Not Found: %s' % self.path)
                return True

        return False
696526
def _get_dest_file_and_url(self, filepath, page_meta={}):
        

        filename = filepath.split("/")[-1]
        filepath_base = filepath.replace(filename, "").rstrip("/")
        slug = page_meta.get("slug")
        fname = slugify(slug) if slug else filename \
            .replace(".html", "") \
            .replace(".md", "") \
            .replace(".jade", "")

        if page_meta.get("pretty_url") is False:
            dest_file = os.path.join(filepath_base, "%s.html" % fname)
        else:
            dest_dir = filepath_base
            if filename not in ["index.html", "index.md", "index.jade"]:
                dest_dir = os.path.join(filepath_base, fname)
            dest_file = os.path.join(dest_dir, "index.html")

        url = "/" + dest_file.replace("index.html", "")
        return dest_file, url
1363383
def get_async(filename):
    

    if os.path.isfile(os.path.join(config.static_folder, filename)):
        return flask.redirect(flask.url_for('static', filename=filename))

    retry_count = int(flask.request.args.get('retry_count', 0))
    if retry_count < 10:
        time.sleep(0.25)  # ghastly hack to get the client to backoff a bit
        return flask.redirect(flask.url_for('async',
                                            filename=filename,
                                            cb=random.randint(0, 2**48),
                                            retry_count=retry_count + 1))

    # the image isn't available yet; generate a placeholder and let the
    # client attempt to re-fetch periodically, maybe
    vals = [int(b) for b in hashlib.md5(
        filename.encode('utf-8')).digest()[0:12]]
    placeholder = PIL.Image.new('RGB', (2, 2))
    placeholder.putdata(list(zip(vals[0::3], vals[1::3], vals[2::3])))
    outbytes = io.BytesIO()
    placeholder.save(outbytes, "PNG")
    outbytes.seek(0)

    response = flask.make_response(
        flask.send_file(outbytes, mimetype='image/png'))
    response.headers['Refresh'] = 5
    return response
1243548
def get(self, host, files_count, path="/", ssl=False, external=None):
        
        theme = "https" if ssl else "http"
        url = host + path
        http_url = theme + "://" + url

        result = {}
        try:
            capture_path = os.getcwd() + '/'

            har_file_path = capture_path + "har/"

            # fc.load_page(self.driver, http_url)
            fc.switch_tab(self.driver)
            self.load_page(http_url)

            print "driver get: " + http_url

            time.sleep(2)

            # if url[-1] == "/":
            #     f_name = url.split('/')[-2]
            # else:
            #     f_name = url.split('/')[-1]

            # fc.save_html(self.driver, f_name, os.path.join(capture_path, "htmls/"))
            # fc.save_screenshot(self.driver, f_name, os.path.join(capture_path, "screenshots/"))

            result = self.wrap_results(url=http_url, files_count=files_count, fd=har_file_path)

            if external is not None:
                external[http_url] = result

        except Exception as e:
            result['error'] = e.message
            print e

        return result
245848
def get_static(self, _, file_name=None):
        
        content_type = {
            'ss': 'text/css',
            'js': 'application/javascript',
        }.get(file_name[-2:])
        if not content_type:
            raise HttpError(HTTPStatus.NOT_FOUND, 42)

        return HttpResponse(self.load_static(file_name), headers={
            'Content-Type': content_type,
            'Content-Encoding': 'gzip',
            'Cache-Control': 'public, max-age=300',
        })
797527
def _url(self, url, file_upload=False):
        

        host = self.api_url
        if file_upload:
            host = self.uploads_api_url

        protocol = 'https' if self.https else 'http'
        if url.endswith('/'):
            url = url[:-1]
        return '{0}://{1}/{2}'.format(
            protocol,
            host,
            url
        )
584951
def refine_get_urls(original):
    

    def get_urls():
        from django.conf.urls import url
        from django.conf import settings
        from django.contrib.staticfiles.urls import staticfiles_urlpatterns
        from django.views.static import serve
        if settings.DEBUG:
            return staticfiles_urlpatterns() + [
                url(r'^media/(?P<path>.*)$', serve, {
                    'document_root': settings.MEDIA_ROOT,
                }),
            ] + original()
        else:
            return original()
    return get_urls
1320472
def SingleStaticServe(file_path):
    
    def get_file():
        mime, encoding = mimetypes.guess_type(file_path)
        fullpath = os.path.join(get_config('project_path'), file_path)
        return open(fullpath, 'rb'), mime or 'application/octet-stream'

    class SingleStaticServe(Program):
        controllers = ['http-get']
        model = [get_file]
        view = FileView()

    return SingleStaticServe()
47441
def get_url(self, filename, query_para=None, **url_args):
        
        from uliweb.core.html import Tag
        
        title = url_args.pop('title', filename)
        text = url_args.pop('text', title)
        query_para = query_para or {}
        return str(Tag('a', title, href=self.get_href(filename, **query_para), **url_args))
648944
def get_from_cache(url):
    
    # if the tool is configured to use the cache
    if settings.use_cache:
        # determine the filename by hashing the url
        filename = hashlib.md5(url.encode('utf-8')).hexdigest()

        cache_path_filename = os.path.join(settings.cache_folder, os.extsep.join([filename, 'json']))
        # open the cache file for this url hash if it already exists, otherwise
        # return None
        if os.path.isfile(cache_path_filename):
            with io.open(cache_path_filename, encoding='utf-8') as cache_file:
                response_json = json.load(cache_file)
            log('Retrieved response from cache file "{}" for URL "{}"'.format(cache_path_filename, url))
            return response_json
203851
def get_download_url(self, instance, default=None):
        
        download = default
        # calculate the download url
        download = "{url}/at_download/{fieldname}".format(
            url=instance.absolute_url(), fieldname=self.get_field_name())
        return download
969089
def get_file_urls(self):
        
        if self.use_bundle:
            return [self.get_url()]
        return [bundle_file.file_url for bundle_file in self.files]
548479
def static(self, uri, file_or_directory, *args, **kwargs):
        
        static = FutureStatic(uri, file_or_directory, args, kwargs)
        self.statics.append(static)
272232
def static_url(redis, path):
    """"""
    file_hash = get_cache_buster(redis, path)
    return "%s/%s?v=%s" % (oz.settings["static_host"], path, file_hash)
268405
def get(url):
    
    url = text_type(url)
    if url.find("://") == -1:
        Log.error("{{url}} must have a prototcol (eg http://) declared", url=url)

    base = URL("")
    if url.startswith("file://") and url[7] != "/":
        if os.sep=="\\":
            base = URL("file:///" + os.getcwd().replace(os.sep, "/").rstrip("/") + "/.")
        else:
            base = URL("file://" + os.getcwd().rstrip("/") + "/.")
    elif url[url.find("://") + 3] != "/":
        Log.error("{{url}} must be absolute", url=url)

    phase1 = _replace_ref(wrap({"$ref": url}), base)  # BLANK URL ONLY WORKS IF url IS ABSOLUTE
    try:
        phase2 = _replace_locals(phase1, [phase1])
        return wrap(phase2)
    except Exception as e:
        Log.error("problem replacing locals in\n{{phase1}}", phase1=phase1, cause=e)
1063852
def base_url(self):
        ''''''
        config_value = self.config.get('url')
        if config_value:
            return self._clean_url(config_value)
        default_url = current_app.config.get('FS_URL')
        default_url = current_app.config.get('{0}URL'.format(self.backend_prefix), default_url)
        if default_url:
            url = urljoin(default_url, self.name)
            return self._clean_url(url)
        return url_for('fs.get_file', fs=self.name, filename='', _external=True)