使用生成器下载文件 和 对文件的权限进行校验
这里是有的是 falcon 框架, 其他框架思路大致一样
from wsgiref import simple_server import falcon import json from falcon_multipart.middleware import MultipartMiddleware import os class ThingsResource(object): def on_post(self, req, resp): try: print(req.headers.get('CONTENT-TYPE')) print(dir(req)) if req.headers.get('CONTENT-TYPE', '') =='application/json': res = req.media else: # res = req.get_param_as_list('upload[]') res = req.params print(res) print(res) print(res.get('upload[]')) res = res.get('upload[]') # res = req.get_param_as_list('upload[]') print(456) path = 'z' for item in res: print(item.filename) with open(path+item.filename, 'wb', 8192) as f: # print(dir(item.file)) for chunk in item.file.readlines(): f.write(chunk) print(item.file.read()) print(dir(item.file)) resp.media = {'name': 'zhangbiao'} resp.status = falcon.HTTP_201 except Exception as e: print(123) print(e) def on_get(self, req, resp): res = open('text1.tx', 'rb') str = '/home/roo/Desktop/projects/lico-confluent-proxy/text1.tx' resp.stream = self.file_iterator(str) resp.downloadable_as = os.path.basename(str) def file_iterator(self,file_name, chunk_size=8192): with open(file_name, mode='rb', buffering=1) as f: while True: c = f.read(chunk_size) if c: yield c else: break # Configure your WSGI server to load "things.app" (app is a WSGI callable) app = falcon.API(middleware=[MultipartMiddleware()]) things = ThingsResource() app.add_route('/upload', things) if __name__ == '__main__': httpd = simple_server.make_server('0.0.0.0', 8000, app) httpd.serve_forever()
校验程序对文件是否有读写权限
检验权限模式
os.access(path,mode)
方法使用当前的uid/gid尝试访问路径。大部分操作使用有效的 uid/gid, 因此运行环境可以在 suid/sgid 环境尝试
参数:
- path --要用来检测是否有访问权限的路径。
- mode --常用4种模式如下:
- os.F_OK:测试path是否存在
- os.R_OK:测试path是否可读
- os.W_OK:测试path是否可写
- os.X_OK:测试path是否可执行
返回值: 如果允许访问则返回True,否则返回False。
import os, sys # 假定 /tmp/foo.txt 文件存在,并有读写权限 ret = os.access("/tmp/foo.txt", os.F_OK) print ("F_OK - 返回值 %s"% ret) ret = os.access("/tmp/foo.txt", os.R_OK) print ("R_OK - 返回值 %s"% ret) ret = os.access("/tmp/foo.txt", os.W_OK) print ("W_OK - 返回值 %s"% ret) ret = os.access("/tmp/foo.txt", os.X_OK) print ("X_OK - 返回值 %s"% ret)
执行以上程序输出结果为:
F_OK - 返回值 True
R_OK - 返回值 True
W_OK - 返回值 True
X_OK - 返回值 False