Flask-Admin 做web文件服务器

之前用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 加入一行即可


                {% block list_header scoped %}
                {% if actions %}
                
                {% endif %}
                
                {% endblock %}
            
...
            

其中

{{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/

你可能感兴趣的:(Flask-Admin 做web文件服务器)

{{ _gettext('Name') }} {{ _gettext('Size') }} {{ _gettext('Date') }}
{{ size|filesizeformat }} {{date|datetime}} {{ _gettext('Date') }}