Ejemplo n.º 1
0
def handler_public(filepath):
    """ Serving static files """
    global DEFAULT_STATIC_FILES_DIR
    # User static files have a higher priority
    if os.path.exists(os.path.join(USER_STATIC_FILES_DIR, filepath)):
        return static_file(filepath, root=USER_STATIC_FILES_DIR)
    return static_file(filepath, root=DEFAULT_STATIC_FILES_DIR)
def send_asset(type_of, filename):
    """Static file routing

    Parameters:
    type_of -- Type of static file, usual choices are css, js, or img
    filename -- filename of the static file including extension
    """
    local_path = os.path.join(PROJECT_ROOT,
                              PROJECT_DIR,
                              "assets",
                              type_of,
                              filename)
    utility_path = os.path.join(UTILITIES_ROOT,
                                "assets",
                                type_of,
                                filename)
    if os.path.exists(utility_path):
        return static_file(filename,
                           root=os.path.join(UTILITIES_ROOT,
                                             "assets",
                                             type_of))
    elif os.path.exists(local_path):
        return static_file(filename,
			   root=os.path.join(PROJECT_ROOT,
                                             PROJECT_DIR,
                                             "assets",
                                             type_of))
Ejemplo n.º 3
0
def get_dataset_schema(did, typ, library):
    """

    :param did:
    :param typ:
    :param library:
    :return:
    """
    from ambry.cache import RemoteMarker

    ct = _get_ct(typ)

    b = library.get(did)

    if not b:
        raise exc.NotFound("No bundle found for id {}".format(did))

    if ct == 'csv':
        from StringIO import StringIO
        output = StringIO()
        response.content_type = 'text/csv'
        b.schema.as_csv(output)
        static_file(output)
    elif ct == 'json':
        import json
        s = b.schema.as_struct()
        return s
    elif ct == 'yaml':
        import yaml
        s = b.schema.as_struct()
        response.content_type = 'application/x-yaml'
        return yaml.dump(s)
    else:
        raise Exception("Unknown format")
Ejemplo n.º 4
0
def index(filename=None):

    if not filename:
        filename = 'index.html'

    elif filename == 'timeout':
        time.sleep(3)
        filename = 'index.html'
    
    elif filename.startswith('attachment'):
        if filename == 'attachment-unquoted':
            bottle.response.headers['content-disposition'] = 'attachment; filename=text-file-unquoted.txt'
            filename = 'text-file.txt'
        else:
            bottle.response.headers['content-disposition'] = 'attachment; filename="text-file.txt"'
            filename = 'text-file.txt'

        bottle.response.content_type = 'text/plain'
        return open(os.path.join(DATA_PATH, filename)).read()      

    elif filename.endswith('.xml.gz'):
        return bottle.static_file(filename, root=DATA_PATH, 
                                mimetype='application/octet-stream')        

    elif filename.endswith('.gz'):
        return bottle.static_file(filename, root=DATA_PATH, 
                                mimetype='application/gzip')        

    elif filename == 'index-western-encoding.html':
        bottle.response.content_type = 'text/html; charset=iso-8859-1'
        return u'This will be sent with ISO-8859-1 encoding.'

    return bottle.static_file(filename, root=DATA_PATH)
Ejemplo n.º 5
0
def get_result_file(jobid, rname, rfname):
    """Get result file <rname>/<rfname> for job <jobid>

    Returns:
        200 OK: file (on success)
        404 Not Found: Job not found (on NotFoundWarning)
        404 Not Found: Result not found (on NotFoundWarning)
        500 Internal Server Error (on error)
    """
    user = set_user()
    # Get job description from DB
    job = Job('', jobid, user, get_parameters=True, get_results=True)
    # Check if result exists
    if rname not in job.results:
        raise storage.NotFoundWarning('Result "{}" NOT FOUND for job "{}"'.format(rname, jobid))
    # Return result
    # rfname = job.get_result_filename(rname)
    #response.content_type = 'text/plain; charset=UTF-8'
    #return str(job.results[result]['url'])
    media_type = job.results[rname]['mediaType']
    logger.debug('{} {} {} {} {}'.format(job.jobname, jobid, rname, rfname, media_type))
    response.set_header('Content-type', media_type)
    if any(x in media_type for x in ['text', 'xml', 'json']):
        return static_file(rfname, root='{}/{}/results'.format(JOBDATA_PATH, job.jobid), mimetype=media_type)
    else:
        return static_file(rfname, root='{}/{}/results'.format(JOBDATA_PATH, job.jobid), mimetype=media_type, download=rfname)
def callback(name):
    db = get_db()
    icon = db.get_icon_path(db.units[name])
    if icon:
        return static_file(icon, root=db.root)
    else:
        return static_file('blank.png', root='./static/')
Ejemplo n.º 7
0
def callback(name):
    db = get_db()
    root, icon = db.get_icon_path(db.units[name])
    if icon:
        return static_file(icon, root=root)
    else:
        return static_file("blank.png", root="./static/")
Ejemplo n.º 8
0
    def execPOST():
        if (not authenticate(request)):
            return parse({
                'status': 'ERROR-AUTHENTICATION',
                'error': 'Invalid authentication.'
            })

        if (request.forms.get('command') == 'download-file'):
            filename = request.forms.get('paramaters')
            return static_file(filename, root=env['VCLONE_REPOSTORY'] + '/files', download=filename)

        if (request.forms.get('command') == 'checkout'):
            checkout(request.forms.get('filename'), request.forms.get('colaborator'), env['VCLONE_REPOSTORY'])

        if (request.forms.get('command') == 'clone'):
            zipfn = clone(request)
            if (isinstance(zipfn, str)):
                return static_file(zipfn, root=env['MAIN'], download=zipfn)
            else:
                return parse(zipfn)

        if (request.forms.get('command') == 'commit-file'):
            return commit(env['VCLONE_REPOSTORY'], request.forms.get('file'), request.forms.get('paramaters'), request.forms.get('collaborator'), request.files.get('fileupload'), request.forms.get('branch'))

        if (request.forms.get('command') == 'create-branch'):
            return createBranch(env['VCLONE_REPOSTORY'], request.forms.get('paramaters'))

        if (request.forms.get('command') == 'remove-branch'):
            return removeBranch(env['VCLONE_REPOSTORY'], request.forms.get('paramaters'))
Ejemplo n.º 9
0
Archivo: main.py Proyecto: kball/ambry
def get_dataset_schema(did, typ, library):
    from ambry.cache import RemoteMarker

    ct = _get_ct(typ)

    b = library.get(did)

    if not b:
        raise exc.NotFound("No bundle found for id {}".format(did))

    if ct == "csv":
        from StringIO import StringIO

        output = StringIO()
        response.content_type = "text/csv"
        b.schema.as_csv(output)
        static_file(output)
    elif ct == "json":
        import json

        s = b.schema.as_struct()
        return s
    elif ct == "yaml":
        import yaml

        s = b.schema.as_struct()
        response.content_type = "application/x-yaml"
        return yaml.dump(s)
    else:
        raise Exception("Unknown format")
Ejemplo n.º 10
0
def callback(path):
    """
    Debug view for serving up static files
    """
    if path.startswith('media/'):
        return static_file(path, root=config.DATA_SOURCE)
    return static_file(path, root=os.path.join(config.LOCAL_PATH, 'static'))
Ejemplo n.º 11
0
def process():
    if int(request.forms.get('num')) == 0:
        return static_file('music-one direction.json', root='./presets')
    if int(request.forms.get('num')) == 1:
        return static_file('music-wu tang clan.json', root='./presets')
    if int(request.forms.get('num')) == 2:
        return static_file('music-taylor swift.json', root='./presets')
Ejemplo n.º 12
0
def process():
    if int(request.forms.get('num')) == 0:
        return static_file('movies-hobbit.json', root='./presets')
    if int(request.forms.get('num')) == 1:
        return static_file('movies-hunger games.json', root='./presets')
    if int(request.forms.get('num')) == 2:
        return static_file('movies-star wars.json', root='./presets')
Ejemplo n.º 13
0
def process():
    if int(request.forms.get('num')) == 0:
        return static_file('programming-c++.json', root='./presets')
    if int(request.forms.get('num')) == 1:
        return static_file('programming-java.json', root='./presets')
    if int(request.forms.get('num')) == 2:
        return static_file('programming-ruby.json', root='./presets')
Ejemplo n.º 14
0
def get_build_file(project=None, branch=None, system=None, fsdate=None, bfile=None):
    """get file for build"""
    validate_build(project, branch, system)

    ext = os.path.splitext(bfile)[1]
    path = config.build_directory(project, branch, system, fsdate)

    if not os.path.exists(path):
        abort(404, "Build does not exist.")

    if bfile == "status.svg":
        response.set_header("Cache-control", "no-cache")
        response.set_header("Pragma", "no-cache")
        if not failure_for_build(project, branch, system, fsdate):
            return static_file("ok.svg", root=rootpath("media", "status"))
        return static_file("fail.svg", root=rootpath("media", "status"))
    elif ext == ".zip":
        return static_file(bfile, root=rootpath(path))
    elif ext == ".bz2":
        return static_file(bfile, root=rootpath(path))
    elif ext == ".txt":
        response.content_type = "text/plain"
        path = rootpath(path, bfile.replace(".txt", ".bz2"))
        if os.path.exists(path):
            return bz2.BZ2File(path).read()

    abort(404, "No such file.")
Ejemplo n.º 15
0
def thumbnailer(url):
    url = url.strip()
    orig = url
    if url.split('.')[-1]:
        url = url.split('.')[0]
    if 'thumb_' + url + '.jpg' in os.listdir(config.Settings['directories']['thumbs']):
        return static_file('thumb_' + url + '.jpg', root='/var/www/bottleimg/img/t')
    else:
        results = config.db.query(
            'SELECT * FROM `keys` WHERE `url` COLLATE utf8_bin LIKE ' + config.dbn.sqlquote(url + '.%'))
        if results:
            for row in results:
                name = row['url']
                orig = row['original'] if row['original'] else row['url']
                try:
                    if 'thumb_' + url + '.jpg' in os.listdir(config.Settings['directories']['thumbs']):
                        return static_file('thumb_' + url + '.jpg', root='/var/www/bottleimg/img/t')
                    else:
                        size = 200, 200
                        base = Image.open(
                            config.Settings['directories']['private'] + name)
                        image_info = base.info
                        if base.mode not in ("L", "RGBA"):
                            base = base.convert("RGBA")
                        base = ImageOps.fit(base, size, Image.ANTIALIAS)
                        # base.thumbnail(size, Image.ANTIALIAS)
                        base.save(config.Settings['directories']['thumbs']
                                  + 'thumb_' + url + '.jpg', **image_info)
                        return static_file('thumb_' + url + '.jpg', root='/var/www/bottleimg/img/t')
                except:
                    abort(404, 'not found')
        else:
            abort(404, 'not found')
Ejemplo n.º 16
0
def get_egg(pkg_name, egg_name):
    config, pkg_idx = request.app.config['config'], request.app.config['pkg_idx']
    log.debug("Package: {} egg:{}".format(pkg_name, egg_name))
    pkg_dir = opath.join(config.nestegg.pypi_dir, pkg_name)
    if not egg_name.startswith(pkg_name) :
        egg_name="{}-{}.".format(pkg_name,egg_name)
        if opath.exists(pkg_dir) :
            for fname in os.listdir(pkg_dir) :
                if fname.startswith(egg_name) and fname != egg_name :
                    egg_name = fname
                    break
    fpath = opath.join(config.nestegg.pypi_dir, pkg_name, egg_name)
    if not opath.exists(fpath) :
        pkg_idx.find_packages(Requirement.parse(pkg_name))
        for dist in pkg_idx[pkg_name] :
            if egg_info(dist.location)[0] == egg_name:
                log.debug("Fetch {}/{}".format(pkg_name,egg_name))
                tmp = tempfile.gettempdir()
                try :
                    shutil.move(pkg_idx.download(dist.location, tmp), fpath)
                    return static_file(egg_name, root=pkg_dir)
                except Exception as _e :
                    pass
        abort(404,"No egg found for {} {}".format(pkg_name,egg_name))
    else :
        return static_file(egg_name, root=pkg_dir)
Ejemplo n.º 17
0
def read(url, size = ''):
    file = prepend_fold(url);
    if(len(size)>0):
        file = zoom(size, url);
        return static_file(file, config('cache_dir'));
    else:
        return static_file(file, config('upload_dir'));
Ejemplo n.º 18
0
def serve_static(path):
    # save if this resource is available as gz
    if path not in GZIPPED:
        GZIPPED[path] = exists(join(APP_ROOT, path + ".gz"))

    # gzipped and clients accepts it
    # TODO: index.html is not gzipped, because of template processing
    gzipped = False
    if GZIPPED[path] and "gzip" in request.get_header("Accept-Encoding", "") and path != "index.html":
        gzipped = True
        path += ".gz"

    resp = static_file(path, root=APP_ROOT)

    # Also serve from .tmp folder in dev mode
    if resp.status_code == 404 and APP_PATH == "app":
        resp = static_file(path, root=join(PROJECT_DIR, '.tmp'))

    if path.endswith(".html") or path.endswith(".html.gz"):
        # tell the browser all html files must be revalidated
        resp.headers["Cache-Control"] = "must-revalidate"
    elif resp.status_code == 200:
        # expires after 7 days
        resp.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
                                                time.gmtime(time.time() + 60 * 60 * 24 * 7))
        resp.headers['Cache-control'] = "public"

    if gzipped:
        resp.headers['Vary'] = 'Accept-Encoding'
        resp.headers['Content-Encoding'] = 'gzip'

    return resp
Ejemplo n.º 19
0
def get_egg(pkg_name, egg_name):
    config, pkg_idx = request.app.config['ctx'], request.app.config['pkg_idx']
    log.debug("Package: {} egg:{}".format(pkg_name, egg_name))
    packages = {normalise(f): f for f in config.pypi_dir.listdir() 
                                    if config.pypi_dir[f].isdir()}
    pkg_name = packages.get(normalise(pkg_name), pkg_name)
    pkg_dir = config.pypi_dir[pkg_name]
    log.debug("package dir is {}".format(pkg_dir))
    if not egg_name.startswith(pkg_name) :
        egg_name="{}-{}.".format(pkg_name,egg_name)
        if pkg_dir.exists() :
            for fname in os.listdir(+pkg_dir) :
                if fname.startswith(egg_name) and fname != egg_name :
                    egg_name = fname
                    break
    fpath = config.pypi_dir[pkg_name][egg_name]
    log.debug("Egg path is {}".format(fpath))
    if not fpath.exists() :
        pkg_idx.find_packages(Requirement.parse(pkg_name))
        for dist in pkg_idx[idx_safe_name(pkg_name)] :
            if egg_info(dist.location)[0] == egg_name:
                log.debug("Fetch {}/{}".format(pkg_name,egg_name))
                tmp = tempfile.gettempdir()
                try :
                    shutil.move(pkg_idx.download(dist.location, tmp), +fpath)
                    return static_file(egg_name, root=+pkg_dir)
                except Exception as _e :
                    pass
        abort(404,"No egg found for {} {}".format(pkg_name,egg_name))
    else :
        return static_file(egg_name, root=+pkg_dir)
Ejemplo n.º 20
0
def sign_up():
    username = bottle.request.forms.get('username')
    password = bottle.request.forms.get('password')
    if login.sign_up(username, password):
        return bottle.static_file("success.html", root=".")
    else:
        return bottle.static_file("index.html", root=".")
Ejemplo n.º 21
0
def send_static_web(filename):
    if os.path.isfile('./web/'+filename):
        return static_file(filename, root='./web')
    else:
        filename = filename+'/index.html'
        if os.path.isfile('./web/'+filename):
            return static_file(filename, root='./web')
    return ''
Ejemplo n.º 22
0
 def test_mime(self):
     """ SendFile: Mime Guessing"""
     f = static_file(os.path.basename(__file__), root='./')
     self.assertTrue(f.header['Content-Type'] in ('application/x-python-code', 'text/x-python'))
     f = static_file(os.path.basename(__file__), root='./', mimetype='some/type')
     self.assertEqual('some/type', f.header['Content-Type'])
     f = static_file(os.path.basename(__file__), root='./', guessmime=False)
     self.assertEqual('text/plain', f.header['Content-Type'])
Ejemplo n.º 23
0
 def test_mime(self):
     """ SendFile: Mime Guessing"""
     f = static_file(os.path.basename(__file__), root="./")
     self.assertTrue(f.headers["Content-Type"] in ("application/x-python-code", "text/x-python"))
     f = static_file(os.path.basename(__file__), root="./", mimetype="some/type")
     self.assertEqual("some/type", f.headers["Content-Type"])
     f = static_file(os.path.basename(__file__), root="./", guessmime=False)
     self.assertEqual("text/plain", f.headers["Content-Type"])
Ejemplo n.º 24
0
 def test_download(self):
     """ SendFile: Download as attachment """
     basename = os.path.basename(__file__)
     f = static_file(basename, root="./", download=True)
     self.assertEqual('attachment; filename="%s"' % basename, f.headers["Content-Disposition"])
     request.environ["HTTP_IF_MODIFIED_SINCE"] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(100))
     f = static_file(os.path.basename(__file__), root="./")
     self.assertEqual(open(__file__, "rb").read(), f.output.read())
Ejemplo n.º 25
0
def login_func():
    username = bottle.request.forms.get('username')
    password = bottle.request.forms.get('password')
    try:
        login.login_user(username, password)
        return bottle.static_file("success.html", root=".")
    except login.LoginError as error:
        return bottle.static_file("login.html", root=".")
Ejemplo n.º 26
0
 def test_download(self):
     """ SendFile: Download as attachment """
     basename = os.path.basename(__file__)
     f = static_file(basename, root='./', download=True)
     self.assertEqual('attachment; filename="%s"' % basename, f.headers['Content-Disposition'])
     request.environ['HTTP_IF_MODIFIED_SINCE'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(100))
     f = static_file(os.path.basename(__file__), root='./')
     self.assertEqual(open(__file__,'rb').read(), f.body.read())
Ejemplo n.º 27
0
 def _serve_static(filepath):
     response = bottle.static_file(filepath,
                                   root=settings.ENGINEER.STATIC_DIR)
     if type(response) is bottle.HTTPError:
         return bottle.static_file(path(filepath) / 'index.html',
                                   root=settings.OUTPUT_DIR)
     else:
         return response
Ejemplo n.º 28
0
 def files(self, filename):
     name, ext = os.path.splitext(filename)
     if ext == ".html":
         return static_file(filename, root=config.local_path + '/webserver/pages')
     elif ext == ".css":
         return static_file(filename, root=config.local_path + '/webserver/style')
     elif ext == ".js":
         return static_file(filename, root=config.local_path + '/webserver/scripts')
Ejemplo n.º 29
0
def site_logos(site_key):
    root = os.path.join(MEDIA_ROOT, 'images/logos')
    filename = '%s.png' % site_key
    path = os.path.join(root, filename)
    if os.path.exists(path):
        return static_file(filename, root=root)
    else:
        return static_file('images/unknown_site_logo.png', root=MEDIA_ROOT)
Ejemplo n.º 30
0
def download(backup):
    if backup == 'db':
        filename = zip_db_photos(UPLOAD_FOLDER, DB_PATH, 'dl/backup.zip')
        return static_file(filename=filename, root='.', download=True)
    if backup == 'all':
        filename = zip_path('.', 'dl/backup.zip')
        return static_file(filename=filename, root='.', download=True)
        # return static_file('shelve.db', root='db', download=True)
    return ''
Ejemplo n.º 31
0
def server_static(part, filename):
    ''' This endpoint serves static files '''
    return static_file(filename, 'static/' + part + '/')
Ejemplo n.º 32
0
 def server_homepage_static(filepath):
     return static_file(filepath, root=ICECREAM_PATH + '/statics/images/')
Ejemplo n.º 33
0
 def _serve_homepage_template():
     __homepage_file = static_file("index.html",
                                   root=ICECREAM_PATH +
                                   '/statics/templates')
     return __homepage_file
Ejemplo n.º 34
0
def ref(filename):
    return bottle.static_file(filename, './ref/')
Ejemplo n.º 35
0
def login():
    return bottle.static_file('login.html', './')
Ejemplo n.º 36
0
def server_static(path):
    return bottle.static_file(path, root='./assets')
Ejemplo n.º 37
0
def load_focus():
    return bottle.static_file('focus.html', './')
Ejemplo n.º 38
0
def stylesheets(filename):
    return static_file(filename, root='css')
Ejemplo n.º 39
0
def javascripts(filename):
    return static_file(filename, root='js')
Ejemplo n.º 40
0
def favicon():
    return static_file("favicon.ico", root=join(PROJECT_DIR, "static", "img"))
Ejemplo n.º 41
0
def images(filename):
    return static_file(filename, root='images')
Ejemplo n.º 42
0
def download(fid, api):
    path, name = api.getFilePath(fid)
    return static_file(name, path, download=True)
Ejemplo n.º 43
0
def server_static(path):
    response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
                                                time.gmtime(time.time() + 60 * 60 * 24 * 7))
    response.headers['Cache-control'] = "public"
    return static_file(path, root=join(PROJECT_DIR, "static"))
Ejemplo n.º 44
0
Archivo: app.py Proyecto: hakjoon/class
def send_static(filename):
    return static_file(filename, root=static_root)
Ejemplo n.º 45
0
def server_static(filepath):
    """Tells bottle where to find css files"""
    return bottle.static_file(filepath, root=join(appPath, 'static/css'))
Ejemplo n.º 46
0
def serve_pictures(slika):
    return bottle.static_file(slika, root='img')
Ejemplo n.º 47
0
def server_static(filename):
    return static_file(filename, root='./views/myfiles')
Ejemplo n.º 48
0
def static(path):
    return bottle.static_file(path, root='static/')
Ejemplo n.º 49
0
def index():
    return static_file("webplugin_example.html",
                       root='/home/django/webplugin/demo')
Ejemplo n.º 50
0
 def __static(self, filename):
   return bottle.static_file(
     filename, root = self.__resources_path)
Ejemplo n.º 51
0
def load_fm():
    return bottle.static_file('fm.html', './')
Ejemplo n.º 52
0
def callback(path):
    return static_file(path, root='static/')
Ejemplo n.º 53
0
def register():
    return bottle.static_file('register.html', './')
Ejemplo n.º 54
0
def test(name, filename):
    return static_file(filename, root='tests/' + name)
Ejemplo n.º 55
0
 def __serve_static_media(filepath):
     return static_file(filepath, root=media_path)
Ejemplo n.º 56
0
def server_static(filename):
    return static_file(filename, root='static/')
Ejemplo n.º 57
0
def webfile(filename):
    return bottle.static_file(filename, root="./webdoc/")  # 相对路径
Ejemplo n.º 58
0
def send_static():
    genreport()
    return static_file("temp-plot.html", root='./')
Ejemplo n.º 59
0
 def get_zip():
     return static_file(os.path.basename(path), os.path.dirname(path))
Ejemplo n.º 60
0
 def send_static(filename):
     return static_file(filename, root=get_static_resource_path('www/'))