Python flask.safe_join() Examples

The following are 13 code examples of flask.safe_join(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: template.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_old_templates(self, upgrade_templates=False):
        old_ids = [t.stem for t
                   in self.template_dir.glob('*' + FileExt.old_template)]
        if len(old_ids) > 0 and upgrade_templates:
            print "Converting {} old style templates".format(len(old_ids))
            for lm_id in old_ids:
                fp = safe_join(str(self.template_dir),
                               lm_id + FileExt.old_template)
                convert_legacy_template(fp)

        elif len(old_ids) > 0:
            print((
                "\nWARNING: ignored {} old style '.txt' templates in '{}' " +
                "({}).\n" +
                "See https://github.com/menpo/landmarkerio-server#templates " +
                "more information. You can restart with the " +
                "'--upgrade-templates' flag to convert them automatically " +
                "(one time operation)\n"
            ).format(
                len(old_ids),
                self.template_dir,
                ", ".join(['{}.txt'.format(t) for t in old_ids]))
            ) 
Example #2
Source File: asset.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def texture_file(self, asset_id):
        return reduce(safe_join, (str(self.cache_dir),
                                  asset_id, CacheFile.texture)) 
Example #3
Source File: asset.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def thumbnail_file(self, asset_id):
        return reduce(safe_join,
                      (str(self.cache_dir), asset_id, CacheFile.thumbnail)) 
Example #4
Source File: asset.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mesh(self, asset_id):
        return reduce(safe_join, (str(self.cache_dir), asset_id,
                                  CacheFile.mesh)) 
Example #5
Source File: template.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_template(self, lm_id):
        fp = safe_join(str(self.template_dir), lm_id + FileExt.template)
        return load_template(fp, self.n_dims) 
Example #6
Source File: landmark.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _lm_paths(self, asset_id=None):
        # what landmarks do exist and where
        if asset_id is None:
            asset_id = '*'
        g = glob.glob(p.join(safe_join(self.lm_dir, asset_id), '*'))
        return filter(lambda f: p.isfile(f) and
                                p.splitext(f)[-1] == FileExt.lm, g) 
Example #7
Source File: landmark.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_lm(self, asset_id, lm_id, lm_json):
        r"""
        Persist a given landmark definition to disk.
        """
        subject_dir = safe_join(self.lm_dir, asset_id)
        if not p.isdir(subject_dir):
            os.mkdir(subject_dir)
        super(SeparateDirFileLmAdapter, self).save_lm(asset_id, lm_id, lm_json) 
Example #8
Source File: models.py    From website with MIT License 5 votes vote down vote up
def full_path(self):
        # build storage path, e.g.
        # /app/uploads/acme/2coffee12345678123123123123123123
        return safe_join(current_app.config["UPLOAD_ROOT"], self.path) 
Example #9
Source File: webhandlers.py    From conducthotline.com with Apache License 2.0 5 votes vote down vote up
def view_page(name):
    markdown_file = flask.safe_join(CONTENT, f"{name}.md")

    if not os.path.exists(markdown_file):
        flask.abort(404)

    with open(markdown_file, "r") as fh:
        content = cmarkgfm.markdown_to_html_with_extensions(
            fh.read(), extensions=["table", "autolink", "strikethrough"]
        )

    # content = content.replace("<h1>", "<h1 class=\"title is-1 is-spaced\">")
    # content = content.replace("<h2>", "<h2 class=\"subtitle is-2 is-spaced\">")

    return flask.render_template("page.html", content=content) 
Example #10
Source File: versioned_static.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_file_hash(filename):
    if not hasattr(g, 'static_hashes'):
        g.static_hashes = {}
    # Check the cache if not in debug mode
    if not current_app.debug:
        try:
            return g.static_hashes[filename]
        except KeyError:
            pass
    hasher = hashlib.md5()
    with open(safe_join(current_app.static_folder, filename), 'rb') as f:
        hasher.update(f.read())
    filehash = hasher.hexdigest()[:8]
    g.static_hashes[filename] = filehash
    return filehash 
Example #11
Source File: api.py    From nidaba with GNU General Public License v2.0 5 votes vote down vote up
def get(self, batch, file):
        """
        Retrieves the file at *file* in batch *batch*.

        ** Request **

        .. sourcecode:: http

            GET /pages/:batch/:path

        ** Response **

        .. sourcecode:: http

            HTTP/1.1 200 OK
            Content-Type: application/octet-stream

            ...

        :param batch: batch's unique id
        :type batch: str
        :param file: path to the batch's file
        :type file: path
        :status 200: No error
        :status 404: File not found
        """
        log.debug('routing to pages with URN: {}/{}'.format(batch, file))
        return send_from_directory(abspath(expanduser(nidaba_cfg['storage_path'])), safe_join(batch, file)) 
Example #12
Source File: plume.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
def static_fetcher(resource_name):
    resource_name = safe_join('static', resource_name)
    if resource_name in application.resources:
        return Response(open(resource_name, mode='rb').read(), status=200, mimetype='application/octet-stream')
    return Response(application.four_o_four, status=404)


# This is where we process a transform request. 
Example #13
Source File: api.py    From multiscanner with Mozilla Public License 2.0 4 votes vote down vote up
def files_get_sha256_helper(sha256, raw='f'):
    '''
    Returns binary from storage. Defaults to password protected zipfile.
    '''
    file_path = safe_join(api_config['api']['upload_folder'], sha256)
    if not os.path.exists(file_path):
        abort(HTTP_NOT_FOUND)

    with open(file_path, 'rb') as fh:
        fh_content = fh.read()

    raw = str(raw)[0].lower()
    if raw in ['t', 'y', '1']:
        response = make_response(fh_content)
        response.headers['Content-Type'] = 'application/octet-stream; charset=UTF-8'
        # better way to include fname?
        response.headers['Content-Disposition'] = 'inline; filename={}.bin'.format(sha256)
    else:
        # ref: https://github.com/crits/crits/crits/core/data_tools.py#L122
        rawname = sha256 + '.bin'
        with open(safe_join('/tmp/', rawname), 'wb') as raw_fh:
            raw_fh.write(fh_content)

        zipname = sha256 + '.zip'
        args = ['/usr/bin/zip', '-j',
                safe_join('/tmp', zipname),
                safe_join('/tmp', rawname),
                '-P', 'infected']
        proc = subprocess.Popen(args)
        wait_seconds = 30
        while proc.poll() is None and wait_seconds:
            time.sleep(1)
            wait_seconds -= 1

        if proc.returncode:
            return make_response(jsonify({'Error': 'Failed to create zip ()'.format(proc.returncode)}))
        elif not wait_seconds:
            proc.terminate()
            return make_response(jsonify({'Error': 'Process timed out'}))
        else:
            with open(safe_join('/tmp', zipname), 'rb') as zip_fh:
                zip_data = zip_fh.read()
            if len(zip_data) == 0:
                return make_response(jsonify({'Error': 'Zip file empty'}))
            response = make_response(zip_data)
            response.headers['Content-Type'] = 'application/zip; charset=UTF-8'
            response.headers['Content-Disposition'] = 'inline; filename={}.zip'.format(sha256)
    return response