Python bottle 模块,static_file() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用bottle.static_file()

项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def get_user_data(filepath):
    user = root.authorized()
    # filepath = request.query.filepath
    # get the owner from the filepath
    # e.g. "user_data/wes/mendel/y23022/file.dat"
    path_list = filepath.split("/")
    owner = path_list[0]
    cid = path_list[2]
    shared = jobs(cid=cid).shared
    # print filepath, path_list, shared

    # only allow admin to see other user's cases that have not been shared
    if owner != user and shared != "True" and user != "admin":
        return template('error', err="access forbidden")

    return static_file(filepath, root=user_dir)
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def zip_case():
    """zip case on machine to prepare for download"""
    user = root.authorized()
    import zipfile
    app = request.query.app
    cid = request.query.cid

    base_dir = os.path.join(user_dir, user, app)
    path = os.path.join(base_dir, cid+".zip")
    zf = zipfile.ZipFile(path, mode='w', compression=zipfile.ZIP_DEFLATED)
    sim_dir = os.path.join(base_dir, cid)
    for fn in os.listdir(sim_dir):
        zf.write(os.path.join(sim_dir, fn))
    zf.close()

    return static_file(path, root="./")
    # status = "case compressed"
    # redirect(request.headers.get('Referer')+"&status="+status)
项目:codex-backend    作者:codexgigassys    | 项目源码 | 文件源码
def export_metadata():
    mdc = MetaController()
    hashes = request.forms.dict.get("file_hash[]")
    dump_to_save = ""
    random_id = id_generator()
    tmp_path = "/tmp/meta_export"
    tmp_folder = os.path.join(tmp_path, random_id)
    call_with_output(["mkdir", "-p", tmp_folder])
    for hash in hashes:
        hash = clean_hash(hash.replace('\r', ''))
        res = mdc.read(hash)
        dump = dumps(res, indent=4)
        file_name = os.path.join(tmp_folder, str(hash) + '.txt')
        fd = open(file_name, "w")
        fd.write(dump)
        fd.close()
    zip_path = os.path.join(tmp_path, random_id + '.zip')
    call_with_output(["zip", "-jr", zip_path, tmp_folder])
    resp = static_file(str(random_id) + '.zip', root=tmp_path, download=True)
    resp.set_cookie('fileDownload', 'true')
    shutil.rmtree(tmp_folder)
    os.remove(zip_path)
    return resp
项目:singing_horse    作者:f0k    | 项目源码 | 文件源码
def main():
    if len(sys.argv) > 1:
        print "Serves the demo. Needs bottle.py to run. Will serve via bjoern"
        print "if installed, otherwise via wsgi_ref. Reads its configuration "
        print "from config.ini."
        return

    # load configuration
    port = int(CONFIG.get('port', 9090))
    staticdir = os.path.join(os.path.dirname(__file__), 'static')

    # start web server
    print "Starting web server on localhost:%d..." % port
    app.route('/static/:path#.+#', callback=lambda path:
            bottle.static_file(path, root=staticdir))
    try:
        import bjoern
    except ImportError:
        bjoern = None
    bottle.run(app, host='localhost', port=port,
            server='bjoern' if bjoern else 'wsgiref')
项目:anxiety    作者:hectron    | 项目源码 | 文件源码
def server_static(filepath):
    """Serves static assets from the directory `equitas/static`.

    This supports returning static files from subdirectories within that
    directory. For example, it allows you to return css stylesheets or even
    javascript files from those directories. For example, in your HTML, you can
    have the following:

        <script src="/static/scripts/something/something_else.js"></script>

    And this would return the script within
    `equitas/static/scripts/something/something_else`.
    """
    this_directory = os.path.dirname(os.path.abspath(__file__))
    static_directory = os.path.join(this_directory, 'anxiety', 'static')

    return static_file(filepath, root=static_directory)


################################################################################
# API for JSON requests
################################################################################
项目:change-acs-password    作者:nertwork    | 项目源码 | 文件源码
def serve_static(filename):
    return static_file(filename, root=path.join(BASE_DIR, 'static'))
项目:modernpython    作者:rhettinger    | 项目源码 | 文件源码
def fetch_static(filename):
    response.set_header('Cache-Control', 'max-age=600')
    return static_file(filename, root='static')
项目:dabdabrevolution    作者:harryparkdotio    | 项目源码 | 文件源码
def server_static(filepath):
    return static_file(filepath, root='/Users/pipskweak/Desktop/web/')
项目:anubad-web    作者:foss-np    | 项目源码 | 文件源码
def server_static(filepath):
    return static_file(filepath, root='./static/')
项目:PyJFuzz    作者:mseclab    | 项目源码 | 文件源码
def custom_html(self, filepath):
        """
        Serve custom HTML page
        """
        try:
            response.headers.append("Access-Control-Allow-Origin", "*")
            response.headers.append("Accept-Encoding", "identity")
            response.headers.append("Content-Type", "text/html")
            return static_file(filepath, root=self.config.html)
        except Exception as e:
            raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
项目:chppL    作者:nocotan    | 项目源码 | 文件源码
def static(filename):
    """static file path"""
    return static_file(filename, root=STATIC)
项目:sysdweb    作者:ogarcia    | 项目源码 | 文件源码
def get_favicon():
    return static_file('favicon.ico', root=os.path.join(static_path, 'img'))
项目:sysdweb    作者:ogarcia    | 项目源码 | 文件源码
def get_css(file):
    return static_file(file, root=os.path.join(static_path, 'css'))
项目:sysdweb    作者:ogarcia    | 项目源码 | 文件源码
def get_fonts(file):
    return static_file(file, root=os.path.join(static_path, 'fonts'))
项目:sysdweb    作者:ogarcia    | 项目源码 | 文件源码
def get_img(file):
    return static_file(file, root=os.path.join(static_path, 'img'))
项目:sysdweb    作者:ogarcia    | 项目源码 | 文件源码
def get_js(file):
    return static_file(file, root=os.path.join(static_path, 'js'))
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
def server_static(filename):
    return static_file(filename, root='./static')
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
def server_static_css(filename):
    return static_file(filename, root='./static/css')
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
def server_static_js(filename):
    return static_file(filename, root='./static/js')
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
def server_static_img(filename):
    return static_file(filename, root='./static/img')
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
def server_static_img(filename):
    return static_file(filename, root='./static/layer')
项目:first_timer_scraper    作者:niccokunzmann    | 项目源码 | 文件源码
def get_static_file(path):
    return static_file(path, root=STATIC_FILES)
项目:first_timer_scraper    作者:niccokunzmann    | 项目源码 | 文件源码
def get_source():
    """Download the source of this application."""
    # from http://stackoverflow.com/questions/458436/adding-folders-to-a-zip-file-using-python#6511788
    directory = tempfile.mkdtemp()
    temp_path = os.path.join(directory, APPLICATION)
    zip_path = shutil.make_archive(temp_path, "zip", HERE)
    return static_file(APPLICATION + ".zip", root=directory)
项目:weppy    作者:santoshphilip    | 项目源码 | 文件源码
def server_static(filepath):
    imgpath = static_file(filepath, root='./%s' % (IMGFOLDER, ))
    return imgpath
项目:henet    作者:AcrDijon    | 项目源码 | 文件源码
def serve_static(filepath):
    return static_file(filepath, root=RESOURCES_PATH)


# make this a plugin
项目:henet    作者:AcrDijon    | 项目源码 | 文件源码
def get_file(filename):
    media_dir = app._config['henet']['media_dir']
    fullpath = os.path.join(media_dir, filename)
    mimetype = guess_type(fullpath)[0]

    return static_file(filename, root=media_dir,
                       mimetype=mimetype)
项目:henet    作者:AcrDijon    | 项目源码 | 文件源码
def get_media_thumbnail(size, filename):
    filename = filename.decode('utf8')

    ext = os.path.splitext(filename)[-1].lower()

    if ext == '.pdf':
        redirect('/resources/images/pdf-200x200.png')
        return

    if ext not in  ('.jpg', '.png', '.jpeg', '.bmp'):
        redirect('/resources/images/blank.png')
        return

    media_dir = app._config['henet']['media_dir']
    thumbnails_dir = app._config['henet']['thumbnails_dir']

    thumbname = size + '-' + filename
    thumbnail_file = os.path.join(thumbnails_dir, thumbname)

    if not os.path.exists(thumbnail_file):
        image_file = os.path.join(media_dir, filename)
        size = [int(i) for i in size.split('x')]
        image = Image.open(image_file)
        image.thumbnail(size)
        image.save(thumbnail_file, 'JPEG')


    mimetype = guess_type(thumbnail_file)[0]
    return static_file(thumbname, root=thumbnails_dir,
                       mimetype=mimetype)
项目:bottle_beginner    作者:denzow    | 项目源码 | 文件源码
def static(file_path):
    """
    ???????????????
    /static/* ???????????????????
    :param file_path:
    :return:
    """
    return static_file(file_path, root="./static")
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def user_data(filepath):
    return static_file(filepath, root='user_data')
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def user_data(filepath):
    return static_file(filepath, root='user_data')

# By default, the server will allow negotiations with extremely old protocols
# that are susceptible to attacks, so we only allow TLSv1.2
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def download(filepath):
    root.authorized()
    return static_file(filepath, root='download', download=filepath)
项目:icfpc2016-judge    作者:icfpc2016    | 项目源码 | 文件源码
def static_handler(path):
    return bottle.static_file(
        path,
        root=os.path.join(os.path.dirname(__file__), '..', 'static'))
项目:indiwebmanager    作者:knro    | 项目源码 | 文件源码
def callback(path):
    """Serve static files"""
    return static_file(path, root=views_path)
项目:indiwebmanager    作者:knro    | 项目源码 | 文件源码
def get_favicon():
    """Serve favicon"""
    return static_file('favicon.ico', root=views_path)
项目:honeyd-python    作者:sookyp    | 项目源码 | 文件源码
def css(filepath):
    return static_file(filepath, root='honeyd/utilities/http/css/')

# main page
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def default_handler():
    return bottle.static_file('app.html', root=os.path.join(conf['rootdir'], 'frontend') )
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def static_bin_handler(file):
    return bottle.static_file(file, root=os.path.join(conf['rootdir'], 'frontend'))
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def static_css_handler(path):
    return bottle.static_file(path, root=os.path.join(conf['rootdir'], 'frontend', 'css'))
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def static_font_handler(path):
    return bottle.static_file(path, root=os.path.join(conf['rootdir'], 'frontend', 'fonts'))
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def static_js_handler(path):
    return bottle.static_file(path, root=os.path.join(conf['rootdir'], 'frontend', 'js'))
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def favicon_handler():
    return bottle.static_file('favicon.ico', root=os.path.join(conf['rootdir'], 'frontend', 'img'))
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def download(filename, dlname):
    print "requesting: " + filename
    return bottle.static_file(filename, root=tempfile.gettempdir(), download=dlname)



### LOW-LEVEL
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def get(jobname='woot'):
    """Get a queue job in .dba format."""
    base, name = os.path.split(_get_path(jobname))
    return bottle.static_file(name, root=base, mimetype='application/json')
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def get_library(jobname):
    """Get a library job in .dba format."""
    base, name = os.path.split(_get_path(jobname, library=True))
    return bottle.static_file(name, root=base, mimetype='application/json')
项目:experiment-manager    作者:softfire-eu    | 项目源码 | 文件源码
def server_static(filename):
    """ route to the css and static files"""
    if ".." in filename:
        return HTTPError(status=403)
    return bottle.static_file(filename, root='%s/static' % get_config('api', 'view-path', '/etc/softfire/views'))


#########
# Utils #
#########
项目:Monitoring    作者:Skydes    | 项目源码 | 文件源码
def server_static(path):
    return bottle.static_file(path, root="./")
项目:Monitoring    作者:Skydes    | 项目源码 | 文件源码
def server_captures(path):
    try:
        return bottle.static_file(path, root="./temp")
    except OSError as err:
        logging.error("Error accessing static file: {message}".format(message=err.strerror))
        return None
项目:movies-python-py2neo-3.0    作者:neo4j-examples    | 项目源码 | 文件源码
def get_index():
    return static_file("index.html", root="static")
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def js_dynamic(path):
    response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
                                                time.gmtime(time.time() + 60 * 60 * 24 * 2))
    response.headers['Cache-control'] = "public"
    response.headers['Content-Type'] = "text/javascript; charset=UTF-8"

    try:
        # static files are not rendered
        if "static" not in path and "mootools" not in path:
            t = env.get_template("js/%s" % path)
            return t.render()
        else:
            return static_file(path, root=join(PROJECT_DIR, "media", "js"))
    except:
        return HTTPError(404, "Not Found")
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
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, "media"))