flask.send_from_directory

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 101

Project: chili
Source File: chili.py
View license
@app.route('/')
def home():
    return send_from_directory(PUBLIC_DIR, 'home-1.html')

Example 102

Project: chili
Source File: chili.py
View license
@app.route(PAGE_LINK_PATTERN % '<path:page_id>')
def page(page_id):
    return send_from_directory(PUBLIC_DIR, 'home-%s.html' % page_id)

Example 103

Project: chili
Source File: chili.py
View license
@app.route(ENTRY_LINK_PATTERN % '<path:filename>')
def post(filename):
    return send_from_directory(LOCAL_ENTRIES_DIR, filename)

Example 104

Project: chili
Source File: chili.py
View license
@app.route(TAG_LINK_PATTERN % '<path:filename>')
def tag(filename):
    return send_from_directory(LOCAL_TAGS_DIR, filename)

Example 105

Project: chili
Source File: chili.py
View license
@app.route('/<path:filename>')
def public(filename):
    return send_from_directory('public', filename)

Example 106

Project: chili
Source File: chili.py
View license
@app.route('/.well-known/<path:filename>')
def for_certbot(filename):
    return send_from_directory('.well-known', filename)

Example 107

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

Example 108

View license
@blueprint.route('/robots.txt')
def static_from_root():
    return send_from_directory(current_app.static_folder, request.path[1:])

Example 109

Project: flyingcloud
Source File: app.py
View license
@app.route('/static/<path:path>')
def send_web(path):
    return send_from_directory('static', path)

Example 110

Project: pysheeet
Source File: app.py
View license
@app.route('/<path:path>')
def static_proxy(path):
    """Static files proxy"""
    return send_from_directory(ROOT, path)

Example 111

Project: pysheeet
Source File: app.py
View license
@app.route('/')
def index_redirection():
    """Redirecting index file"""
    return send_from_directory(ROOT, 'index.html')

Example 112

Project: gitric
Source File: app.py
View license
@app.route("/parrots/<path:path>")
def parrot(path):
    return send_from_directory(os.path.join('parrots', 'parrots'), path)

Example 113

Project: FuzzLabs
Source File: webserver.py
View license
@app.route("/<path:filename>", methods=['GET'])
@headers
@validate
def base_static(filename):
    return send_from_directory(app.root_path + '/static/', filename)

Example 114

Project: debsources
Source File: views.py
View license
    @app.route('/javascript/<path:path>')
    def javascript(path):
        return flask.send_from_directory('/usr/share/javascript/', path)

Example 115

Project: debsources
Source File: views.py
View license
    @app.route('/icons/<path:path>')
    def icons(path):
        return flask.send_from_directory('/usr/share/icons/', path)

Example 116

Project: knowledge-repo
Source File: web_editor.py
View license
@blueprint.route('/file_upload', methods=['POST', 'GET'])
@PageView.logged
def file_upload():
    """ Uploads images dropped on the web editor's markdown box to static/images
        and notifies editors by email
    """
    upload_folder = 'images'
    title = request.form['title']
    files = request.files
    uploadedFiles = []

    if files:
        for img_file in files.values():
            filename = secure_filename(title + "_" + img_file.filename).lower()
            dst_folder = os.path.join(current_app.static_folder, upload_folder)

            if is_allowed_image_format(img_file):
                try:
                    img_file.save(os.path.join(dst_folder, filename))
                    send_from_directory(dst_folder, filename)
                    uploadedFiles += [url_for("static", filename=os.path.join(upload_folder, filename))]
                except Exception as e:
                    error_msg = "ERROR during image upload: {}".format(str(e))
                    logger.error(error_msg)
                    return json.dumps({'error_msg': error_msg, 'success': False})

            elif is_pdf(filename):
                from PyPDF2 import PdfFileReader
                try:
                    src_pdf = PdfFileReader(img_file)
                    filename = os.path.splitext(filename)[0]
                    num_pages = src_pdf.getNumPages()
                    for page_num in range(num_pages):
                        page_png = pdf_page_to_png(src_pdf, page_num)
                        page_name = "{filename}_{page_num}.jpg".format(**locals())
                        page_png.save(filename=os.path.join(dst_folder, page_name))
                        uploadedFiles += [url_for("static", filename=os.path.join(upload_folder, page_name))]
                except Exception as e:
                    error_msg = "ERROR during pdf upload: {}".format(str(e))
                    logger.error(error_msg)
                    return json.dumps({'error_msg': error_msg, 'success': False})

    return json.dumps({'links': uploadedFiles, 'success': True})

Example 117

Project: vqa-mcb
Source File: server.py
View license
@app.route('/viz/<filename>')
def get_visualization(filename):
    return send_from_directory(VIZ_FOLDER, filename)

Example 118

Project: histsync
Source File: app.py
View license
@app.route('/download-client/<part>')
def download_client(part):
    if part not in ['bash-preexec.sh', 'histsync-client', 'install.bash']:
        abort(404)
    return send_from_directory('.', part)

Example 119

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

Example 120

Project: ipcampy
Source File: dashboard.py
View license
@app.route("/get-image/<int:cam_index>/<day>/<hour>/<image>")
def get_image(cam_index, image, day, hour):
    serve_path = app.store_path+"/"+app.cams[cam_index - 1].cam_id+"/"+day+"/"+hour
    return send_from_directory(serve_path, image)

Example 121

Project: BB-8
Source File: hello.py
View license
@app.route('/')
def hello():
    return send_from_directory('html','index.html')

Example 122

Project: BB-8
Source File: hello.py
View license
@app.route('/js/<path:path>')
def send_js(path):
  return send_from_directory('js', path)

Example 123

Project: BB-8
Source File: hello.py
View license
@app.route('/images/<path:path>')
def send_image(path):
  return send_from_directory('images', path)

Example 124

Project: BB-8
Source File: hello.py
View license
@app.route('/control')
def touchController():
  return send_from_directory('html', 'TouchControl.html')

Example 125

View license
    def get_signed_url_for_submission_file(self):
        """ Gets the signed URL for the specified file """
        try:
            self.s3manager = s3UrlHandler()
            file_name = request.args.get('file') + ".csv"
            submission_id = request.args.get('submission')
            submission = self.jobManager.getSubmissionById(submission_id)
            # Check that user has access to submission
            # If they don't, throw an exception
            self.check_submission_permission(submission)

            if self.isLocal:
                return send_from_directory(self.serverPath, file_name)
            else:
                report_path = self.s3manager.getSignedUrl("errors", file_name, method="GET")
                return redirect(report_path)
        except ResponseException as e:
            return JsonResponse.error(e,StatusCode.CLIENT_ERROR)
        except Exception as e:
            # Unexpected exception, this is a 500 server error
            return JsonResponse.error(e,StatusCode.INTERNAL_ERROR)

Example 126

Project: trappist
Source File: test_app.py
View license
@app.route('/download')
def download():
    test_app_dir = os.path.abspath(os.path.dirname(__file__))
    return send_from_directory(test_app_dir, 'ewok.jpg', as_attachment=True)

Example 127

Project: open-event-orga-server
Source File: content.py
View license
    @expose('/translation_uploads/<path:l_code>', methods=['GET', 'POST'])
    def download(self,l_code):
        file_destination = BASE_TRANSLATIONS_DIR + "/" + l_code + "/LC_MESSAGES"
        return send_from_directory(directory=file_destination, filename="messages.po")

Example 128

View license
@app.route('/pic/<path:filename>')
@auto.doc()
def send_pic(filename):
    """Returns image"""
    return send_from_directory(os.path.realpath('.') + '/static/', filename)

Example 129

View license
@app.route('/calendar/<path:filename>')
@auto.doc()
def send_cal(filename):
    """Returns calendar"""
    return send_from_directory(os.path.realpath('.') + '/static/', filename)

Example 130

View license
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.dirname(os.path.dirname(__file__)) + '/static/', 'favicon.ico',
                               mimetype='image/vnd.microsoft.icon')

Example 131

Project: Frozen-Flask
Source File: __init__.py
View license
    def make_static_app(self):
        """Return a Flask application serving the build destination."""
        root = os.path.join(
            self.app.root_path,
            self.app.config['FREEZER_DESTINATION']
        )

        def dispatch_request():
            filename = self.urlpath_to_filepath(request.path)

            # Override the default mimeype from settings
            guessed_type, guessed_encoding = mimetypes.guess_type(filename)
            if not guessed_type:
                guessed_type = self.app.config['FREEZER_DEFAULT_MIMETYPE']

            return send_from_directory(root, filename, mimetype=guessed_type)

        app = Flask(__name__)
        # Do not use the URL map
        app.dispatch_request = dispatch_request
        return app

Example 132

Project: flask-todo
Source File: app.py
View license
def initialize_app(settings):
    global app
    app = Flask(__name__)
    app.config.from_object(settings)

    # ORDER MIGHT BE IMPORTANT BELOW THIS LINE
    # install extensions and import modules that do registrations
    # the `import x; x` idiom silences pyflakes etc

    import models ; models # must import models before we can init logging, so logging can count queries
    initialize_logging(settings)
    import views ; views
    import assets ; assets
    import api ; api
    import auth ; auth

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(Path(app.root_path)/'static', 'favicon.ico', mimetype='image/vnd.microsoft.icon')

    return app

Example 133

Project: Data-Pipeline
Source File: __main__.py
View license
@app.route('/favicon.ico')
def Favicon():
  """Handler of the favicon request."""
  return flask.send_from_directory(app.root_path, 'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

Example 134

Project: remarks
Source File: main.py
View license
@app.route('/theme/<name>/<path:filename>')
def theme(name, filename):
    theme_dir = os.path.join(instance_path, 'themes', name)
    log.info('Theme file: %s/%s', theme_dir, filename)
    return send_from_directory(theme_dir, filename)

Example 135

Project: fuwa
Source File: app.py
View license
@app.route('/<dirname>')
@app.route('/<dirname>/<filename>')
def getFile(dirname, filename=None):
    """
    Flie delivery to the client.
    """
    if not checkFileName(dirname.split('.')[0]):
        abort(410)
    if filename:
        # If dir and filename  is provided, serve it directly
        return send_from_directory('static/files/%s' % dirname, filename)
    elif not filename:
        # Otherwise, find the filename and redirect back with it
        if os.path.exists('static/files/%s' % dirname):
            files = os.listdir('static/files/%s' % dirname)
            if files:
                # redirect back
                return redirect(url_for('getFile', dirname=dirname, filename=files[0]))
        else:
            abort(404)

Example 136

Project: flask-restaction
Source File: api.py
View license
    def meta_view(self):
        """
        Meta data / API document

        By default, this view func will return API document(HTML),
        you can set request header `Accept` to `application/json`
        or set query string `json` to get meta data(JSON).
        """
        mediatype = request.accept_mimetypes.best_match(
            ['text/html', 'application/json'], default='text/html')
        dumped = json.dumps(
            self.meta, indent=4, sort_keys=True, ensure_ascii=False)
        if mediatype == 'application/json' or 'json' in request.args:
            return make_response(dumped, {
                "Content-Type": "application/json; charset=utf-8"
            })
        filename = request.args.get('f')
        if filename in ["res.js", "res.min.js"]:
            # cache parsed meta
            if self._resjs_cache is None:
                self._resjs_cache = parse_meta(self.meta)
            prefix = current_app.config.get("API_URL_PREFIX")
            min = filename == "res.min.js"
            code = generate_code(self._resjs_cache, prefix=prefix, min=min)
            response = make_response(code, {
                "Content-Type": "application/javascript"
            })
            # handle etag
            response.add_etag()
            return response.make_conditional(request)
        if filename:
            return send_from_directory(DOCS_DIST, basename(filename))
        with open(DOCS_HTML) as f:
            content = f.read()\
                .replace('$(title)', self.meta.get('$title', ''))\
                .replace('$(meta)', dumped)
        return make_response(content)

Example 137

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

Example 138

Project: maple-blog
Source File: __init__.py
View license
@app.route('/robots.txt')
@app.route('/favicon.ico')
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])

Example 139

Project: GraphDash
Source File: routes.py
View license
@app.route('/data/<path:filename>')
def get_data(filename):
    ext = op.splitext(filename)[1].lower()
    return send_from_directory(CONF['root'], filename, mimetype=MIMETYPES.get(ext))

Example 140

Project: GraphDash
Source File: routes.py
View license
@app.route('/assets/<path:filename>')
@cache(60)  # 1 min cache cache to avoid problems on assets update
def get_asset(filename):
    return send_from_directory(ASSETS, filename)

Example 141

Project: Loxo
Source File: loxoapi.py
View license
@app.route('/loxo/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

Example 142

Project: progressivis
Source File: views.py
View license
@progressivis_bp.route('/progressivis/static/<path:filename>')
def progressivis_file(filename):
    return send_from_directory(JS_DIR, filename)

Example 143

Project: progressivis
Source File: views.py
View license
@progressivis_bp.route('/progressivis/static/<path:filename>')
def progressivis_file(filename):
    return send_from_directory(JS_DIR, filename)

Example 144

Project: progressivis
Source File: views.py
View license
@progressivis_bp.route('/favicon.ico')
@progressivis_bp.route('/progressivis/favicon.ico')
def favicon():
    return send_from_directory(JS_DIR, 'favicon.ico', mimetype='image/x-icon')

Example 145

Project: progressivis
Source File: views.py
View license
@progressivis_bp.route('/favicon.ico')
@progressivis_bp.route('/progressivis/favicon.ico')
def favicon():
    return send_from_directory(JS_DIR, 'favicon.ico', mimetype='image/x-icon')

Example 146

View license
@app.route('/images/<path:path>')
def serve_img(path):
    return send_from_directory('static/images/train2014/', path)

Example 147

Project: irrexplorer
Source File: www.py
View license
def create_app(pgdb, configfile=None):
    app = Flask('IRRExplorer')
    app.config.from_pyfile('appconfig.cfg')
    Bootstrap(app)

    @app.route("/robots.txt")
    def static_from_root():
        return send_from_directory(app.static_folder, request.path[1:])

    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = InputForm()
        if request.method == 'GET':
            return render_template('index.html', form=form)

        if request.method == 'POST':
            # note: the form won't submit with empty data, so we don't have to handle that
            data = form.field.data
            print 'Form data:', data

            try:
                sv = utils.classifySearchString(data)
                return redirect(url_for('search', data=sv.value))

            except ValueError as e:
                flash('Invalid search data: ' + str(e))
                return render_template('index.html', form=form)

    # -- search --
    @app.route('/search/<path:data>')
    @app.route('/search/', defaults={'data': None})
    @app.route('/search', defaults={'data': None})
    def search(data):

        query_data = request.args.get('data')
        if query_data:
            # this means that we got search request
            print 'query data', query_data
            return redirect(url_for('search', data=query_data))

        if not data:
            flash('No search data provided')
            return render_template('search.html')

        try:
            sv = utils.classifySearchString(data)

            # prevent people from killing the machine by searching through all prefixes in one query
            if type(sv) is Prefix and '/' in sv.value and int(sv.value.split('/',2)[-1]) < 15:
                flash('Only prefixes longer than /15 are searchable (kills the database)')
                return render_template('search.html')

            tables = []

            # page: title (object type : data)

            # json url for each table, not per report...
            # stuff that is needed per table:
            # id (tables.key)
            # name
            # source url
            # column ordering (first, and last, we cannot do complete until we get results)
            # note (optional)

            if type(sv) is Prefix:
                title = 'Prefix: ' + sv.value
                tables.append({
                    'id'           : 'prefixes',
                    'title'        : 'Matching prefixes',
                    'url'          : '/json/prefix/' + sv.value,
                    'start_fields' : ["prefix", "bgp" ]
                })

            if type(sv) is ASNumber:
                title = 'AS Number: ' + data
                tables.append({
                    'id'           : 'prefixes',
                    'title'        : 'Prefixes',
                    'url'          : '/json/as_prefixes/' + str(sv.value),
                    'start_fields' : ["prefix", "bgp" ],
                    'note'         : 'Offending prefixes are only found if initial prefix sets is smaller than 1000'
                })

            if type(sv) is ASMacro:
                title = 'AS Macro: ' + data
                tables.append({
                    'id'           : 'expanded',
                    'title'        : 'Macro Expansion',
                    'url'          : '/json/macro_expand/' + sv.value,
                    'start_fields' : ["as_macro", "depth", "path", "source", "members"],
                    'note'         : 'AS Macro expansion is limited to 10K rows'
                })

            if type(sv) in (ASNumber, ASMacro):
                key = 'AS' + str(sv.value) if type(sv) is ASNumber else str(sv.value)
                tables.append({
                    'id'           : 'macros',
                    'title'        : 'Included in the following macros:',
                    'url'          : '/json/macro_contain/' + key,
                    'start_fields' : ["as_macro" ]
                })

            return render_template('search.html', title=title, tables=tables)


        except ValueError as e:
            flash('Invalid search data: ' + str(e))
            return render_template('search.html')


    # -- json reports --

    @app.route('/json/prefix/<path:prefix>')
    def prefix(prefix):
        data = report.prefix(pgdb, prefix)
        return json.dumps(data)

    @app.route('/json/as_prefixes/<path:as_number>')
    def as_prefixes(as_number):
        data = report.as_prefixes(pgdb, int(as_number))
        return json.dumps(data)

    @app.route('/json/macro_expand/<path:as_macro>')
    def macro_expand(as_macro):
        data = report.macro_expand(pgdb, as_macro)
        return json.dumps(data)

    @app.route('/json/macro_contain/<path:as_object>')
    def as_contain(as_object):
        data = report.macro_contain(pgdb, as_object)
        return json.dumps(data)

    return app

Example 148

Project: irrexplorer
Source File: www.py
View license
def create_app(pgdb, configfile=None):
    app = Flask('IRRExplorer')
    app.config.from_pyfile('appconfig.cfg')
    Bootstrap(app)

    @app.route("/robots.txt")
    def static_from_root():
        return send_from_directory(app.static_folder, request.path[1:])

    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = InputForm()
        if request.method == 'GET':
            return render_template('index.html', form=form)

        if request.method == 'POST':
            # note: the form won't submit with empty data, so we don't have to handle that
            data = form.field.data
            print 'Form data:', data

            try:
                sv = utils.classifySearchString(data)
                return redirect(url_for('search', data=sv.value))

            except ValueError as e:
                flash('Invalid search data: ' + str(e))
                return render_template('index.html', form=form)

    # -- search --
    @app.route('/search/<path:data>')
    @app.route('/search/', defaults={'data': None})
    @app.route('/search', defaults={'data': None})
    def search(data):

        query_data = request.args.get('data')
        if query_data:
            # this means that we got search request
            print 'query data', query_data
            return redirect(url_for('search', data=query_data))

        if not data:
            flash('No search data provided')
            return render_template('search.html')

        try:
            sv = utils.classifySearchString(data)

            # prevent people from killing the machine by searching through all prefixes in one query
            if type(sv) is Prefix and '/' in sv.value and int(sv.value.split('/',2)[-1]) < 15:
                flash('Only prefixes longer than /15 are searchable (kills the database)')
                return render_template('search.html')

            tables = []

            # page: title (object type : data)

            # json url for each table, not per report...
            # stuff that is needed per table:
            # id (tables.key)
            # name
            # source url
            # column ordering (first, and last, we cannot do complete until we get results)
            # note (optional)

            if type(sv) is Prefix:
                title = 'Prefix: ' + sv.value
                tables.append({
                    'id'           : 'prefixes',
                    'title'        : 'Matching prefixes',
                    'url'          : '/json/prefix/' + sv.value,
                    'start_fields' : ["prefix", "bgp" ]
                })

            if type(sv) is ASNumber:
                title = 'AS Number: ' + data
                tables.append({
                    'id'           : 'prefixes',
                    'title'        : 'Prefixes',
                    'url'          : '/json/as_prefixes/' + str(sv.value),
                    'start_fields' : ["prefix", "bgp" ],
                    'note'         : 'Offending prefixes are only found if initial prefix sets is smaller than 1000'
                })

            if type(sv) is ASMacro:
                title = 'AS Macro: ' + data
                tables.append({
                    'id'           : 'expanded',
                    'title'        : 'Macro Expansion',
                    'url'          : '/json/macro_expand/' + sv.value,
                    'start_fields' : ["as_macro", "depth", "path", "source", "members"],
                    'note'         : 'AS Macro expansion is limited to 10K rows'
                })

            if type(sv) in (ASNumber, ASMacro):
                key = 'AS' + str(sv.value) if type(sv) is ASNumber else str(sv.value)
                tables.append({
                    'id'           : 'macros',
                    'title'        : 'Included in the following macros:',
                    'url'          : '/json/macro_contain/' + key,
                    'start_fields' : ["as_macro" ]
                })

            return render_template('search.html', title=title, tables=tables)


        except ValueError as e:
            flash('Invalid search data: ' + str(e))
            return render_template('search.html')


    # -- json reports --

    @app.route('/json/prefix/<path:prefix>')
    def prefix(prefix):
        data = report.prefix(pgdb, prefix)
        return json.dumps(data)

    @app.route('/json/as_prefixes/<path:as_number>')
    def as_prefixes(as_number):
        data = report.as_prefixes(pgdb, int(as_number))
        return json.dumps(data)

    @app.route('/json/macro_expand/<path:as_macro>')
    def macro_expand(as_macro):
        data = report.macro_expand(pgdb, as_macro)
        return json.dumps(data)

    @app.route('/json/macro_contain/<path:as_object>')
    def as_contain(as_object):
        data = report.macro_contain(pgdb, as_object)
        return json.dumps(data)

    return app

Example 149

Project: disco-dop
Source File: parse.py
View license
@APP.route('/parser/favicon.ico')
def favicon():
	"""Serve the favicon."""
	return send_from_directory(os.path.join(APP.root_path, 'static'),
			'parse.ico', mimetype='image/vnd.microsoft.icon')

Example 150

Project: disco-dop
Source File: parse.py
View license
@APP.route('/parser/static/main.js')
def javascript():
	"""Serve javascript."""
	return send_from_directory(os.path.join(APP.root_path, 'static'),
			'main.js', mimetype='text/javascript')