带上传的HTTP文件服务器脚本(Bottle)
scturtle
posted @ 2011年9月08日 16:23
in python
, 4400 阅读
轻量级的框架当然要用来做轻量级的事了!
尝试用 Bottle 做一个类似 Python 自带的 SimpleHTTPServer.py 的东西,记得有人给 SimpleHTTPServer.py 加过上传功能,看了 Bottle 后觉得可以用很少量的代码实现,而且文档里都有上传的例子了(囧)。
单文件的 Bottle 再加一个 50 行的脚本这样的组合也不比 SimpleHTTPServer.py 差多少,而且还可以随用随改,自用蛮方便的。
updated at 2013.5.8: 在 win 下,os 的函数的输入输出都是 gbk 编码的,所以有一些恶心的 hack ……
# coding: utf-8 from bottle import * import os import sys from os.path import abspath, basename, join, isfile, isdir basepath = abspath(sys.argv[1] if len(sys.argv) > 1 else '.') struct = ''' <!doctype html> <html> <head> <meta charset=utf-8> <title>Directory listing for {path}</title> </head> <body> <h2>Directory listing for {path}</h2> <hr><ul> {lis} </ul><hr> <form action="" method="post" enctype="multipart/form-data"> Upload file: <input type="file" name="file"/> <input type="submit" value="submit"> </form> </body> </html> ''' li = '<li><a href="{name}">{name}</a>' @get('/<path:re:.*>') def main(path): if sys.platform.startswith('win'): # f**k gbk path = path.decode('utf8').encode('gbk') curpath = join(basepath, path) if isfile(curpath): return static_file(path, root=basepath, download=path) childs = [join(curpath, c) for c in os.listdir(curpath)] dirs = filter(isdir, childs) if path: dirs = ['..'] + dirs files = filter(isfile, childs) lis = [li.format(name=basename(d)+'/') for d in dirs] lis += [li.format(name=basename(f)) for f in files] if sys.platform.startswith('win'): # f**k gbk path = path.decode('gbk').encode('utf8') lis = [l.decode('gbk').encode('utf8') for l in lis] return struct.format(path=path if path else '/', lis='\n'.join(lis)) @post('/<path:re:.*>') def upload(path): upfile = request.files.get('file') filename = join(basepath, path, upfile.filename) if sys.platform.startswith('win'): # f**k gbk filename = filename.decode('utf8').encode('gbk') outfile = open(filename, 'wb') try: buf = upfile.file.read(upfile.bufsize) while buf: outfile.write(buf) buf = upfile.file.read(upfile.bufsize) outfile.close() return 'Uploaded %s !' % upfile.filename except Exception, e: print e.message return 'Failed in uploading %s !' % upfile.filename if __name__ == '__main__': debug(True) run(reloader=True, host='0.0.0.0', port=8080)
2022年9月18日 23:12
Final examinations for the second term or the entire year are set up as Summative Assessment-2 Examination tests for all students in the board's regional districts and the schools they attend. CBSE sa 2 Question Paper Class 5 Subject matter experts and educators from numerous institutions advise Team 2 or SA 2 to use practise questions and answers for all languages and disciplines covered by the course, which are based on the updated curriculum. Based on the revised exam structure, sample papers with model sets are recommended for each chapter for all the course's stated topics.