之前用python -m SimpleHTTPServer 命令快速起一個(gè)webserver還是覺得很好用的政鼠,但是缺少upload 的功能頗感遺憾。 最近研究Flask-Admin 的時(shí)候發(fā)現(xiàn)有個(gè) FileAdmin的class队魏,挺適合做文件服務(wù)器的公般。
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()
略微有個(gè)小遺憾,在顯示文件只有Name 和Size胡桨,并沒有文件的修改時(shí)間官帘。我看了下源代碼, 發(fā)現(xiàn)get_files
函數(shù)其實(shí)是有收集修改時(shí)間的 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}}
是我手動(dòng)添加的 刽虹。 用到了一個(gè)customized datetime的filter,因?yàn)?code>last_modified = op.getmtime(fp) 返回的是一個(gè)float類型變量呢诬,需要進(jìn)行轉(zhuǎn)換成更可讀的時(shí)間, 代碼如下
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 命令上傳文件到這個(gè)webserver上呢涌哲,可以參考下面的例子
curl -F "upload=@c:\b.txt" http://localhost:5000/admin/fileadmin/upload/