Flask-Admin 做web檔案伺服器

weixin_34185560發表於2017-02-27

之前用python -m SimpleHTTPServer 命令快速起一個webserver還是覺得很好用的,但是缺少upload 的功能頗感遺憾。 最近研究Flask-Admin 的時候發現有個 FileAdmin的class,挺適合做檔案伺服器的。

Flask-Admin github: https://github.com/flask-admin/flask-admin

安裝flask-admin命令:

pip install flask-admin 

程式碼如下:

from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import Admin
from flask import Flask
import os
from flask_script import Shell, Manager

app=Flask(__name__)
# get base location of current file
basedir=os.path.abspath(os.path.dirname(__file__))

# app configuration
app.config['SECRET_KEY']='!@$RFGAVASDGAQQQ'

admin = Admin(app, name='File', template_mode='bootstrap3')
path=os.path.join(basedir, 'static')
admin.add_view(FileAdmin(basedir,  name='Static Files'))
manager = Manager(app)
manager.run()

略微有個小遺憾,在顯示檔案只有Name 和Size,並沒有檔案的修改時間。我看了下原始碼, 發現get_files函式其實是有收集修改時間的 op.getmtime(fp),只是沒有暴露出來

def get_files(self, path, directory):
        """
            Gets a list of tuples representing the files in the `directory`
            under the `path`

            :param path:
                The path up to the directory

            :param directory:
                The directory that will have its files listed

            Each tuple represents a file and it should contain the file name,
            the relative path, a flag signifying if it is a directory, the file
            size in bytes and the time last modified in seconds since the epoch
        """
        items = []
        for f in os.listdir(directory):
            fp = op.join(directory, f)
            rel_path = op.join(path, f)
            is_dir = self.is_dir(fp)
            size = op.getsize(fp)
            last_modified = op.getmtime(fp)
            items.append((f, rel_path, is_dir, size, last_modified))
        return items

修改list.html 加入一行即可

<table class="table table-striped table-bordered model-list">
        <thead>
            <tr>
                {% block list_header scoped %}
                {% if actions %}
                <th class="list-checkbox-column">
                    <input type="checkbox" name="rowtoggle" class="action-rowtoggle" />
                </th>
                {% endif %}
                <th class="col-md-1"> </th>
                <th>{{ _gettext('Name') }}</th>
                <th>{{ _gettext('Size') }}</th>
                <th>{{ _gettext('Date') }}</th>
                {% endblock %}
            </tr>
        </thead>
...
            <td>
                {{ size|filesizeformat }}
            </td>
             <td>
                {{date|datetime}}
            </td>

其中 <th>{{ _gettext('Date') }}</th>{{date|datetime}} 是我手動新增的 。 用到了一個customized datetime的filter,因為last_modified = op.getmtime(fp) 返回的是一個float型別變數,需要進行轉換成更可讀的時間, 程式碼如下


def format_datetime(value):
    """
    define a filters for jinjia2 to format the unix timestamp (float) to humman readabl
    """
    return datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S')

#set the filter we just created 
env = app.jinja_env
env.filters['datetime'] = format_datetime

如何通過curl 命令上傳檔案到這個webserver上呢,可以參考下面的例子
curl -F "upload=@c:\b.txt" http://localhost:5000/admin/fileadmin/upload/

相關文章