Here are the examples of the python api flask.send_from_directory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

190 Examples 7

Example 51

Project: build-relengapi
Source File: __init__.py
View license
@bp.route('/static', defaults={'path': ''})
def static(path):
    # the Blueprint's static_folder can't depend on app configuration, so we
    # just implement static files directly
    support = get_support()
    return send_from_directory(support.staticdir, path)

Example 52

Project: searx
Source File: webapp.py
View license
def favicon():
    return send_from_directory(os.path.join(app.root_path,

Example 53

Project: bibserver
Source File: ingest.py
View license
def data_serve(filename):
    path = config['download_cache_directory']
    if not path.startswith('/'):
        path = os.path.join(os.getcwd(), path)
    response = send_from_directory(path, filename)
    response.headers['Content-Type'] = 'text/plain'
    return response

Example 54

Project: pyCA
Source File: ui.py
View license
def serve_image(img):
    '''Serve the preview image with the given id
    filepath = ''
        preview_dir = config['capture']['preview_dir']
        filepath = config['capture']['preview'][int(img)]
        filepath = filepath.replace('{{previewdir}}', preview_dir)
        if os.path.isfile(filepath):
            [directory, filename] = filepath.rsplit('/', 1)
            return send_from_directory(directory, filename)
    return '', 404

Example 55

Project: picoCTF-Platform-2
Source File: autogen.py
View license
def serve_autogen_hook(path):
    pid = request.args.get("pid", None)
    static = request.args.get("static", "false") == "true"

    tid = api.user.get_team()["tid"]

    if pid not in api.problem.get_unlocked_pids(tid):
        return WebError("You have not unlocked this problem!")

    instance_number = api.autogen.get_instance_number(pid, tid)

    if static:
        instance_path = api.autogen.get_static_instance_path(pid, public=True)
        instance_path = api.autogen.get_instance_path(pid, instance_number, public=True)

    mime = guess_mimetype(path)
    if mime == 'text/html':
        return send_from_directory(instance_path, path, mimetype=None, as_attachment=False, attachment_filename=None)
        return send_from_directory(instance_path, path, mimetype=mime)

Example 56

Project: auacm
Source File: util.py
View license
def serve_html(filename):
    '''Serve static HTML pages.'''
    return send_from_directory(app.static_folder+"/html/", filename)

Example 57

Project: auacm
Source File: util.py
View license
def serve_info_pdf(pid):
    '''Serve static PDFs.'''
    return send_from_directory(join(app.config['DATA_FOLDER'],
                                    'problems', pid), 'info.pdf')

Example 58

Project: auth0-python
Source File: server.py
View license
def static_files(filename):
    return send_from_directory('./public', filename)

Example 59

Project: SSH-Ranking
Source File: serv.py
View license
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])

Example 60

Project: puffin
Source File: view.py
View license
def media(path):
    if not path[-3:] in ("png", "jpg"):
        raise Exception("Unsupported media file format")
    return send_from_directory(APPLICATION_HOME, path)

Example 61

Project: pureelk
Source File: app.py
View license
def index():
    return send_from_directory(app.static_folder, "index.html")

Example 62

Project: pureelk
Source File: app.py
View license
def css(filename):
    return send_from_directory(os.path.join(app.static_folder, 'css'), filename)

Example 63

Project: pureelk
Source File: app.py
View license
def fonts(filename):
    return send_from_directory(os.path.join(app.static_folder, 'fonts'), filename)

Example 64

Project: pureelk
Source File: app.py
View license
def js(filename):
    return send_from_directory(os.path.join(app.static_folder, 'js'), filename)

Example 65

Project: pureelk
Source File: app.py
View license
def img(filename):
    return send_from_directory(os.path.join(app.static_folder, 'img'), filename)

Example 66

Project: pureelk
Source File: app.py
View license
def webapp(filename):
    return send_from_directory(os.path.join(app.static_folder, 'webapp'), filename)

Example 67

Project: Pushjet-Server-Api
Source File: application.py
View license
def robots_txt():
    return send_from_directory(app.static_folder, request.path[1:])

Example 68

Project: PyClassLessons
Source File: app.py
View license
def send_assets(path):
    return send_from_directory('assets', path)

Example 69

Project: quokka
Source File: views.py
View license
@roles_accepted('admin', 'developer')
def template_files(filename):
    template_path = os.path.join(current_app.root_path,
    return send_from_directory(template_path, filename)

Example 70

Project: quokka
Source File: views.py
View license
def media(filename):
    return send_from_directory(current_app.config.get('MEDIA_ROOT'), filename)

Example 71

Project: quokka
Source File: views.py
View license
def static_from_root():
    return send_from_directory(current_app.static_folder, request.path[1:])

Example 72

Project: box-designer-website
Source File: server.py
View license
@app.route("/", methods=['GET','POST'])
def index():
    if request.method == 'POST':
        validation_errors = _validate_box_params()
        if len(validation_errors)>0:
            error_str = ' '.join(validation_errors)
            logger.debug("Errors: "+error_str)
            return render_template('home.html', error=error_str)
            box_name = _box_name()
            logger.debug('Creating box '+box_name+"...")
            # convert it to millimeters
            measurements = ['width','height','depth','material_thickness','cut_width','notch_length']
            conversion = 1.0
            if request.form['units']=='in':
                conversion = 25.4
            elif request.form['units']=='cm':
                conversion = 10.0
            params = {}
            for key in measurements:
                params[key] = float(request.form[key])*conversion
            # and add bounding box option
            params['bounding_box'] = True if 'bounding_box' in request.form else False
            # now render it
            logger.info( request.remote_addr + " - " + box_name )
            _render_box(box_name, params)
            return send_from_directory(BOX_TMP_DIR,box_name,as_attachment=True)
        return render_template("home.html",
            boxmaker_version = boxmaker.APP_VERSION)

Example 73

Project: MonitorDarkly
Source File: serve.py
View license
def create_and_serve_pic():

    f = open('amount.txt', 'rb')
    amount = int(f.read())

    gif_name = str(amount) + '.gif'
    if not os.path.isfile(os.path.join(STATIC_PATH, gif_name)):
        # Format number
        locale.setlocale(locale.LC_ALL, '')
        formatted_num = locale.currency(amount, grouping=True) + " USD"

        # Generate pic
        img = Image.new('RGB', (500, 500), (255, 255, 255))
        fnt = ImageFont.truetype(os.path.join(FONT_PATH, 'arialbd.ttf'), 25)
        # get a drawing context
        d = ImageDraw.Draw(img)
        # draw text, half opacity
        d.text((1, 0), formatted_num, font=fnt, fill=(51, 51, 51))
        # Crop to text
        (txt_width, txt_height) = d.textsize(formatted_num, font=fnt)
        print txt_height, txt_width
        # if txt_width % 2 == 0
        img = img.crop((0, 0, 300, 26))
        # else:
            # img = img.crop((0, 0, txt_width+1, 26))

        # print "width, height" + str(width) + ", " + str(height)

        baseheight = OUT_HEIGHT
        hpercent = (baseheight / float(img.size[1]))
        wsize = int((float(img.size[0]) * float(hpercent)))
        img = img.resize((wsize, baseheight), Image.ANTIALIAS)

        f, img_name = mkstemp(suffix='.png')

        # Convert to gif
        build_upload_gif(134, 330, img_name, os.path.join(STATIC_PATH, gif_name),
                         clut_offset=17, sdram_offset=0x1000>>6, tile=1)

    return send_from_directory(STATIC_PATH, gif_name)

Example 74

Project: rootio_web
Source File: views.py
View license
def avatar(user_id, filename):
    dir_path = os.path.join(APP.config['UPLOAD_FOLDER'], 'user_%s' % user_id)
    return send_from_directory(dir_path, filename, as_attachment=True)

Example 75

Project: pybossa
Source File: uploads.py
View license
def uploaded_file(filename):  # pragma: no cover
    """Return uploaded file."""
    return send_from_directory(uploader.upload_folder, filename)

Example 76

Project: angular-flask
Source File: controllers.py
View license
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),

Example 77

Project: Deerlet
Source File: main.py
View license
@app.route("/download", methods=['GET'])
def download():
    read_password = current_app.config.get('READ_PASSWORD')
    if not read_password or session.get('read_password') == read_password:
        input_filename = 'resume.md'
        output_filename = 'resume.pdf'

        with open(input_filename, 'r') as stream:
            html_text = markdown(stream.read(), output_format='html4')
        # render the html template
        output = render_template('pdf_template.html', yue_css=yue_css,

        # generate pdf file
        pdfkit.from_string(output, output_filename, options=current_app.config.get('PDF_OPTIONS'), )

        return send_from_directory(current_app.config.get('UPLOAD_FOLDER'),
                                   'resume.pdf', as_attachment=True)
        return redirect(url_for("resume"))

Example 78

Project: image-scanner
Source File: rest.py
View license
def send_js(path):
    ''' Returns a file from the reports dir '''
    return send_from_directory('/var/tmp/image-scanner/reports/', path)

Example 79

Project: utter-va
Source File: __init__.py
View license
def favicon():
	return send_from_directory(os.path.join(app.root_path, 'static'), 'img/favicon.ico')

Example 80

Project: tarbell
Source File: app.py
View license
    def preview(self, path=None, extra_context=None, publish=False):
        Serve up a project path
            self.call_hook("preview", self)

            if path is None:
                path = 'index.html'

            # Detect files
            filepath, mimetype = self._resolve_path(path)

            # Serve dynamic
            if filepath and mimetype and mimetype in self.project.TEMPLATE_TYPES:
                context = self.get_context(publish)
                    "PATH": path,
                    "PREVIEW_SERVER": not publish,
                    "TIMESTAMP": int(time.time()),
                if extra_context:

                rendered = render_template(path, **context)
                return Response(rendered, mimetype=mimetype)

            # Serve static
            if filepath:
                dir, filename = os.path.split(filepath)
                return send_from_directory(dir, filename)

        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
                # Find template with name of error
                cls = e.__class__
                ex_type, ex, tb = sys.exc_info()

                context = self.project.DEFAULT_CONTEXT
                    'PATH': path,
                    'traceback': traceback.format_exception(ex_type, ex, tb),
                    'e': e,
                if extra_context:

                    error_path = '_{0}.{1}.html'.format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)
                except TemplateNotFound:
                    # Find template without underscore prefix, @TODO remove in v1.1
                    error_path = '{0}.{1}.html'.format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)

                return Response(rendered, mimetype="text/html")
            except TemplateNotFound:
                # Otherwise raise old error
                raise ex_type, ex, tb

        # Last ditch effort -- see if path has "index.html" underneath it
        if not path.endswith("index.html"):
            if not path.endswith("/"):
                path = "{0}/".format(path)
            path = "{0}{1}".format(path, "index.html")
            return self.preview(path)

        # It's a 404
        if path.endswith('/index.html'):
            path = path[:-11]
        rendered = render_template("404.html", PATH=path)
        return Response(rendered, status=404)

Example 81

Project: nbdiff
Source File: local_server.py
View license
def nbdiff_static(filename):
    return send_from_directory(os.path.dirname(os.path.realpath(__file__))
                               + '/static', filename)

Example 82

Project: Flask-Store
Source File: __init__.py
View license
    def register_route(self, app):
        """ Registers a default route for serving uploaded assets via
        Flask-Store, this is based on the absolute and relative paths
        defined in the app configuration.

        app : flask.app.Flask
            Flask application instance

        def serve(filename):
            return send_from_directory(app.config['STORE_PATH'], filename)

        # Only do this if the Provider says so
        if self.Provider.register_route:
            url = urlparse.urljoin(
                app.config['STORE_URL_PREFIX'].lstrip('/') + '/',
            app.add_url_rule('/' + url, 'flask.store.file', serve)

Example 83

Project: xcolors
Source File: xcolors.py
View license
def download(filename):
    return send_from_directory('themes', filename,

Example 84

Project: matplotlib-style-gallery
Source File: app.py
View license
    def _add_url_rules(self, app):

        def route_css_files(filename):
            directory = pth.join(disk.root_dir, 'static/css')
            return flask.send_from_directory(directory, filename)

        def route_build_files(filename):
            directory = pth.join(disk.root_dir, 'build')
            return flask.send_from_directory(directory, filename)

        def render():
            return self.render()

        @app.route('/', methods=['POST'])
        def update_styles():
            stylesheet = request.form['input-stylesheet']
            self._input_status = save_scratch_plots(stylesheet)
            self._input_stylesheet = stylesheet
            return self.render()

Example 85

Project: Wallace
Source File: custom.py
View license
def static_from_root():
    """"Serve robots.txt from static file."""
    return send_from_directory('static', request.path[1:])

Example 86

Project: white
Source File: front.py
View license
def content_asset(asset):
    return send_from_directory(current_app.config['CONTENT_PATH'], asset)

Example 87

Project: flask-project-template
Source File: views.py
View license
def static_from_root():
    # Static items
    return send_from_directory(current_app.static_folder, request.path[1:])

Example 88

Project: iiif
Source File: iiif_testserver.py
View license
def serve_static(filename=None, prefix=None, basedir=''):
    """Handler for static files under basedir."""
    return send_from_directory(os.path.join('third_party', prefix),

Example 89

Project: cert-viewer
Source File: views.py
View license
def favicon():
    return send_from_directory(safe_join(app.root_path, 'static/img'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

Example 90

Project: blockstack-core
Source File: index.py
View license
def favicon():
    return send_from_directory(app.static_folder, 'favicon.ico')

Example 91

Project: robotframework-hub
Source File: app.py
View license
    def _favicon(self):
        static_dir = os.path.join(self.app.root_path, 'static')
        return flask.send_from_directory(os.path.join(self.app.root_path, 'static'),
                                         'favicon.ico', mimetype='image/vnd.microsoft.icon')

Example 92

Project: bokeh
Source File: docserver.py
View license
def send_pic(filename):
    return flask.send_from_directory(
        os.path.join(_basedir,"sphinx/_build/html/"), filename)

Example 93

Project: bokeh
Source File: docserver.py
View license
def send_script(filename):
    return flask.send_from_directory(
        os.path.join(_basedir,"sphinx/_build/html/scripts/"), filename)

Example 94

Project: badwolf
Source File: views.py
View license
@blueprint.route('/build/<sha>', methods=['GET'])
def build_log(sha):
    log_dir = os.path.join(current_app.config['BADWOLF_LOG_DIR'], sha)
    return send_from_directory(log_dir, 'build.html')

Example 95

Project: badwolf
Source File: views.py
View license
@blueprint.route('/lint/<sha>', methods=['GET'])
def lint_log(sha):
    log_dir = os.path.join(current_app.config['BADWOLF_LOG_DIR'], sha)
    return send_from_directory(log_dir, 'lint.html')

Example 96

Project: urlmeme
Source File: url.py
View license
def favicon():
    path = os.path.join(app.root_path, 'static')
    mimetype = 'image/vnd.microsoft.icon'
    return send_from_directory(path, 'favicon.ico', mimetype=mimetype)

Example 97

Project: osf.io
Source File: __init__.py
View license
def addon_static(addon, filename):
    addon_path = os.path.join(addon_base_path, addon, 'static')
    return send_from_directory(addon_path, filename)

Example 98

Project: osf.io
Source File: views.py
View license
def resolve_guid(guid, suffix=None):
    """Load GUID by primary key, look up the corresponding view function in the
    routing table, and return the return value of the view function without
    changing the URL.

    :param str guid: GUID primary key
    :param str suffix: Remainder of URL after the GUID
    :return: Return value of proxied view function
    # Look up GUID
    guid_object = Guid.load(guid)
    if guid_object:

        # verify that the object implements a GuidStoredObject-like interface. If a model
        #   was once GuidStoredObject-like but that relationship has changed, it's
        #   possible to have referents that are instances of classes that don't
        #   have a deep_url attribute or otherwise don't behave as
        #   expected.
        if not hasattr(guid_object.referent, 'deep_url'):
                'Guid `{}` resolved to an object with no deep_url'.format(guid)
            raise HTTPError(http.NOT_FOUND)
        referent = guid_object.referent
        if referent is None:
            logger.error('Referent of GUID {0} not found'.format(guid))
            raise HTTPError(http.NOT_FOUND)
        if not referent.deep_url:
            raise HTTPError(http.NOT_FOUND)
        if isinstance(referent, PreprintService):
            return send_from_directory(
                os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['preprints']['path'])),
        url = _build_guid_url(urllib.unquote(referent.deep_url), suffix)
        return proxy_url(url)

    # GUID not found; try lower-cased and redirect if exists
    guid_object_lower = Guid.load(guid.lower())
    if guid_object_lower:
        return redirect(
            _build_guid_url(guid.lower(), suffix)

    # GUID not found
    raise HTTPError(http.NOT_FOUND)

Example 99

Project: wharf
Source File: favicon.py
View license
def favicon():
    return send_from_directory(path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

Example 100

Project: flaskgur
Source File: flaskgur.py
View license
def return_pic(filename):
	return send_from_directory(app.config['UPLOAD_DIR'], secure_filename(filename))