Flask-AutoIndex

Flask-AutoIndex generates an index page for your Flask application automatically. The result just like mod_autoindex, but the look is more awesome! Look at this:

The screenshot of index page generated by Flask-AutoIndex

This module contains pre-designed template and css file. It is default style, but you can make your own style.

Note

Flask-AutoIndex uses Flask-Silk to serve icons. Per default, the icons from Mark James’s Silk icon set are used. These icons are licensed under Creative Commons Attribution 2.5 License or 3.0 License. Before using the icons, read the license.

Installation

Install Flask-AutoIndex with easy_install or pip command:

$ easy_install Flask-AutoIndex
$ pip install Flask-AutoIndex

or check out development version:

$ git clone git://github.com/sublee/flask-autoindex.git

How to Use

Flask-AutoIndex is easy and extensible. It supports flask application.

We will make the application in flask application. There is a basic usage:

import os.path
from flask import Flask
from flask.ext.autoindex import AutoIndex

app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir)

if __name__ == '__main__':
    app.run()

After running the application, http://localhost/ serves a generated index page which contains the file and directory list in current directory.

Customizing

Routing a specified URL

Just like a nomal flask application or module. Follow the below example:

@app.route('/helloworld')
def helloworld():
    return 'Hello, world!', 200

http://localhost/helloworld will serve Hello, world! not /helloworld directory.

Adding an icon rule

If you want to present *.feed files with rss.png icon and present a directory named picture with folder_picture.png icon, follow the below example:

idx.add_icon_rule('rss.png', ext='feed')
idx.add_icon_rule('folder_picture.png', dirname='pictures')

You can change the root directory’s icon to your own icon:

idx.add_icon_rule('http://example.org/favicon.ico', cls=RootDirectory)

Also you can add the more complex rule with a function:

import re
def is_flaskext(ent):
    return isinstance(ent, Directory) and re.match('[Ff]lask-', ent.name)
idx.add_icon_rule('http://example.org/flask-extenstion.png', is_flaskext)

Here is a nice example for changing directory’s icon to its favicon.ico file if it exists:

def get_favicon(ent):
    favicon = 'favicon.ico'
    if type(ent) is Directory and favicon in ent:
        return '/' + os.path.join(ent.path, favicon)
    return False
idx.add_icon_rule(get_favicon)

Changing Silk’s path

AutoIndex has **silk_options keyword arguments for Silk. If you want to use the another path for serving silk icons, use silk_path keyword argument:

idx = AutoIndex(app, silk_path='/myicons')

Now you can get a silk icon from http://localhost/myicons/folder.png not http://localhost/__icons__/folder.png.

See also

The documentation for Flask-Silk

Redesigning the template

AutoIndex.render_autoindex() finds the template from the application’s template directory first. When you made the autoindex.html to the application’s template directory, AutoIndex.render_autoindex() renders your template:

- myapplication
  - templates
    - autoindex.html
  - __init__.py
  - views.py

Your templates could extend the default Flask-AutoIndex’s template, it named __autoindex__/autoindex.html. Here is a basic example:

{% extends '__autoindex__/autoindex.html' %}

{% block meta %}
  {{ super() }}
  <link rel="stylesheet"
    href="{{ url_for('static', filename='myautoindex.css') }}" />
{% endblock %}

{% block header %}
  <div style="width: 500px; margin: 30px auto;">
    <h2>My Application</h2>
{% endblock %}

{% block footer %}
  </div>
{% endblock %}

To get extra fields through to your template, pass them in the template_context keyword argument:

AutoIndex(app, template_context = dict(SITENAME = 'My cool site'))

API

Configuration

class flask_autoindex.AutoIndex(base, browse_root=None, add_url_rules=True, template_context=None, silk_options=None, show_hidden=False)

This class makes the Flask application to serve automatically generated index page. The wrapped application will route / and /<path:path> when add_url_rules is True. Here’s a simple example:

app = Flask(__name__)
AutoIndex(app, '/home/someone/public_html', add_url_rules=True)
Parameters:
  • base – a Flask application.
  • browse_root – a path which is served by root address.
  • add_url_rules – if it is True, the wrapped application routes / and /<path:path> to autoindex. default is True.
  • template_context – would be passed to the Jinja2 template when rendering an AutoIndex page.
  • silk_options – keyword options for flask.ext.silk.Silk.
add_icon_rule(icon, rule=None, ext=None, mimetype=None, name=None, filename=None, dirname=None, cls=None)

Adds a new icon rule.

There are many shortcuts for rule. You can use one or more shortcuts in a rule.

rule

A function which returns True or False. It has one argument which is an instance of Entry. Example usage:

def has_long_name(ent):
    return len(ent.name) > 10
idx.add_icon_rule('brick.png', rule=has_log_name)

Now the application represents files or directorys such as very-very-long-name.js with brick.png icon.

ext

A file extension or file extensions to match with a file:

idx.add_icon_rule('ruby.png', ext='ruby')
idx.add_icon_rule('bug.png', ext=['bug', 'insect'])
mimetype

A mimetype or mimetypes to match with a file:

idx.add_icon_rule('application.png', mimetype='application/*')
idx.add_icon_rule('world.png', mimetype=['image/icon', 'x/*'])
name

A name or names to match with a file or directory:

idx.add_icon_rule('error.png', name='error')
idx.add_icon_rule('database.png', name=['mysql', 'sqlite'])
filename
Same as name, but it matches only a file.
dirname
Same as name, but it matches only a directory.

If icon is callable, it is used to rule function and the result is used to the url for an icon. This way is useful for getting an icon url dynamically. Here’s a nice example:

def get_favicon(ent):
    favicon = 'favicon.ico'
    if type(ent) is Directory and favicon in ent:
        return '/' + os.path.join(ent.path, favicon)
    return False
idx.add_icon_rule(get_favicon)

Now a directory which has a favicon.ico guesses the favicon.ico instead of silk’s folder.png.

render_autoindex(path, browse_root=None, template=None, template_context=None, endpoint='.autoindex', show_hidden=None, sort_by='name', mimetype=None)

Renders an autoindex with the given path.

Parameters:
  • path – the relative path.
  • browse_root – if it is specified, it used to a path which is served by root address.
  • template – the template name.
  • template_context – would be passed to the Jinja2 template when rendering an AutoIndex page.
  • endpoint – an endpoint which is a function.
  • show_hidden – whether to show hidden files (starting with ‘.’)
  • sort_by – the property to sort the entrys by.
  • mimetype – set static mime type for files (no auto detection).

Models

class flask_autoindex.Entry(path, rootdir=None, autoindex=None)

This class wraps file or directory. It is an abstract class, but it returns a derived instance. You can make an instance such as:

directory = Entry('/home/someone/public_html')
assert isinstance(foler, Directory)
file = Entry('/home/someone/public_html/favicon.ico')
assert isinstance(file, File)
classmethod add_icon_rule(icon, rule=None)

Adds a new icon rule globally.

classmethod add_icon_rule_by_class(icon, _class)

Adds a new icon rule by the class globally.

classmethod add_icon_rule_by_name(icon, name)

Adds a new icon rule by the name globally.

guess_icon()

Guesses an icon from itself.

is_root()

Returns True if it is a root directory.

modified

Returns modified time of this.

class flask_autoindex.File(path, rootdir=None, autoindex=None)

This class wraps a file.

classmethod add_icon_rule_by_ext(icon, ext)

Adds a new icon rule by the file extension globally.

classmethod add_icon_rule_by_mimetype(icon, mimetype)

Adds a new icon rule by the mimetype globally.

data

Data of this file.

mimetype

A mimetype of this file.

size

A size of this file.

class flask_autoindex.Directory(path, rootdir=None, autoindex=None)

This class wraps a directory.

explore(sort_by='name', order=1, show_hidden=False)

It is a generator. Each item is a child entry.

get_child(childname)

Returns a child file or directory.

class flask_autoindex.RootDirectory(path, autoindex=None)

This class wraps a root directory.

Template

Blocks

meta
The innerHTML of <head>.
header
The top of <body>.
table
The table for the entry list.
footer
The bottom of <body>.

Variables

curdir
The current directory object.
entries
The child entry list of curdir.
sort_by
The sorting key.
order
Ascending order(1) or Descending order(-1).
endpoint
The endpoint which renders a generated page.

Licensing and Author

This project is licensed under BSD. See LICENSE for the details.

I’m Heungsub Lee. Any regarding questions or patches are welcomed.

Indices and tables

Fork me on GitHub