flask 文件 服务器,Flask-Admin 做web文件服务器

之前用python -m SimpleHTTPServer 命令快速起一个webserver还是觉得很好用的,但是缺少upload 的功能颇感遗憾。 最近研究Flask-Admin 的时候发现有个 FileAdmin的class,挺适合做文件服务器的。

安装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 %}

{{ _gettext('Name') }}{{ _gettext('Size') }}{{ _gettext('Date') }}

{% endblock %}

...

{{ size|filesizeformat }}

{{date|datetime}}

其中

{{ _gettext('Date') }} 和 {{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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值